@wildshard/engine 0.1.18 → 0.1.19

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 (293) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/budgets/shard-size-baseline.json +10 -4
  3. package/index.html +6 -4
  4. package/lint/engine-sides.json +14 -0
  5. package/lint/ratchet.json +0 -68
  6. package/lint/ratchet.mjs +1 -4
  7. package/package.json +17 -15
  8. package/scripts/agent-sync.mjs +27 -8
  9. package/scripts/app-build/appCook.ts +8 -2
  10. package/scripts/app-build/catalogue.ts +10 -7
  11. package/scripts/app-build/gen.ts +22 -2
  12. package/scripts/app-build/isolation.d.mts +10 -0
  13. package/scripts/app-build/isolation.mjs +47 -0
  14. package/scripts/app-build/outputProducts.mjs +4 -0
  15. package/scripts/app-build/previousDeploy.d.mts +2 -0
  16. package/scripts/app-build/previousDeploy.mjs +10 -1
  17. package/scripts/app-build/serviceWorker.ts +10 -3
  18. package/scripts/app-build/splitOutput.mjs +4 -2
  19. package/scripts/app-build/standaloneOutput.d.mts +1 -1
  20. package/scripts/app-build/standaloneOutput.mjs +5 -3
  21. package/scripts/app-build/titlePreloads.d.mts +8 -0
  22. package/scripts/app-build/titlePreloads.mjs +69 -0
  23. package/scripts/app-build/worldMapAtlas.ts +10 -6
  24. package/scripts/app-build-pipeline.mjs +31 -3
  25. package/scripts/built-product.mjs +1 -1
  26. package/scripts/cell-mem-bench.mjs +81 -23
  27. package/scripts/check-custom-sections-zero.mjs +1 -1
  28. package/scripts/check-devserver.mjs +2 -0
  29. package/scripts/check-models.mjs +2 -0
  30. package/scripts/check-paths.allow.json +0 -115
  31. package/scripts/check-paths.mjs +2 -2
  32. package/scripts/check-platform-ratchets.mjs +2 -3
  33. package/scripts/chromium-keychain.d.mts +1 -1
  34. package/scripts/ci-static.sh +1 -1
  35. package/scripts/committed-fast-checks.mjs +0 -2
  36. package/scripts/content-sw-proof.mjs +2 -1
  37. package/scripts/cook-worker.mjs +9 -3
  38. package/scripts/cook.mjs +18 -5
  39. package/scripts/docs-inputs-proof.mjs +6 -6
  40. package/scripts/e7-voice-staging-proof.mjs +1 -1
  41. package/scripts/gate-related-tests.mjs +1 -1
  42. package/scripts/git-source-view.mjs +1 -1
  43. package/scripts/goldens/capture.mjs +17 -5
  44. package/scripts/grid-crossing-nightly.mjs +59 -0
  45. package/scripts/grid-crossing-qa.mjs +44 -0
  46. package/scripts/grid-crossing-ratchet.d.mts +6 -0
  47. package/scripts/grid-crossing-ratchet.mjs +52 -0
  48. package/scripts/grid-crossing-report.mjs +122 -0
  49. package/scripts/grid-crossing-stages.mjs +47 -0
  50. package/scripts/grid-crossing-tour.mjs +277 -0
  51. package/scripts/grid-crossing-walk-proof.mjs +124 -17
  52. package/scripts/host-ruler/roots.mjs +2 -2
  53. package/scripts/host-ruler.d.mts +91 -0
  54. package/scripts/host-ruler.mjs +565 -0
  55. package/scripts/live-prepush.py +3 -5
  56. package/scripts/loading-flow/benchmax.mjs +3 -1
  57. package/scripts/look-loop/test_look_loop.py +1 -38
  58. package/scripts/memory-proof.mjs +61 -6
  59. package/scripts/mmo-bots.mjs +8 -2
  60. package/scripts/net-lag-proof.mjs +219 -0
  61. package/scripts/night-market-kit-budget.mjs +2 -2
  62. package/scripts/offline-proof-rules.d.mts +2 -2
  63. package/scripts/offline-proof-rules.mjs +15 -4
  64. package/scripts/offline-proof.mjs +74 -13
  65. package/scripts/{shard-platform-output.mjs → output-reader.mjs} +1 -1
  66. package/scripts/page-release/content.d.mts +9 -1
  67. package/scripts/page-release/content.mjs +131 -17
  68. package/scripts/page-release/flow.mjs +36 -10
  69. package/scripts/page-release/stamp-content.mjs +24 -0
  70. package/scripts/page-release.mjs +28 -6
  71. package/scripts/page-size.mjs +2 -1
  72. package/scripts/pin-packs.ts +1 -1
  73. package/scripts/pins.ts +4 -4
  74. package/scripts/precommit-checks.mjs +1 -7
  75. package/scripts/precommit-jobs.mjs +0 -1
  76. package/scripts/precommit-source.py +1 -9
  77. package/scripts/program-discovery.mjs +1 -1
  78. package/scripts/ring-cook.mjs +2 -1
  79. package/scripts/ring-step.ts +1 -1
  80. package/scripts/script-scenario-metrics.mjs +1 -1
  81. package/scripts/shard-output-content.d.mts +1 -1
  82. package/scripts/shard-output-content.mjs +2 -2
  83. package/scripts/shard-outputs.mjs +1 -1
  84. package/scripts/shard-public.mjs +1 -1
  85. package/scripts/shard-wire-meter.mjs +24 -9
  86. package/scripts/side-parity.mjs +4 -2
  87. package/scripts/standalone-smoke.mjs +8 -3
  88. package/scripts/tier-textures.mjs +22 -4
  89. package/scripts/tile-bake-report.mjs +1 -1
  90. package/scripts/tile-bakes.mjs +1 -1
  91. package/scripts/title-assets.generated.json +2 -0
  92. package/scripts/tsconfig.json +0 -2
  93. package/scripts/vendor/basisu/LICENSE +201 -0
  94. package/scripts/vendor/basisu/basis_encoder.cjs +2 -0
  95. package/scripts/vendor/basisu/basis_encoder.wasm +0 -0
  96. package/scripts/vitest-push-guards.config.ts +1 -1
  97. package/scripts/vps/harden-apply.sh +4 -1
  98. package/scripts/vps/harden-prometheus.sh +176 -0
  99. package/scripts/vps/harden.sh +16 -0
  100. package/scripts/vps/rebuild.sh +18 -0
  101. package/scripts/vps/wildshard-config +6 -2
  102. package/scripts/worker-client-play.mjs +6 -2
  103. package/scripts/worktree-reap.mjs +5 -5
  104. package/src/.oxlintrc.json +3 -182
  105. package/src/client/app/entry.ts +10 -2
  106. package/src/client/engine/boot/bootCache.ts +2 -2
  107. package/src/client/engine/boot/bootTrace.ts +12 -4
  108. package/src/client/engine/boot/browserChunkRecovery.ts +4 -0
  109. package/src/client/engine/boot/clearDownloads.ts +5 -2
  110. package/src/client/engine/boot/contentRead.ts +11 -0
  111. package/src/client/engine/boot/gpuFiles.ts +4 -2
  112. package/src/client/engine/boot/lastEnd.ts +99 -12
  113. package/src/client/engine/boot/texturePack.ts +2 -2
  114. package/src/client/engine/net/netPlayer.ts +19 -2
  115. package/src/client/engine/net/otherPlayers.ts +55 -8
  116. package/src/client/engine/net/predictor.ts +33 -9
  117. package/src/client/engine/net/redial.ts +29 -6
  118. package/src/client/engine/pwa/cacheNames.ts +58 -1
  119. package/src/client/engine/pwa/sw.js +41 -11
  120. package/src/client/engine/render/dataLook.ts +152 -40
  121. package/src/client/engine/render/families/detail.ts +89 -0
  122. package/src/client/engine/render/families/pbr.ts +7 -1
  123. package/src/client/engine/render/look.ts +6 -0
  124. package/src/client/engine/render/lookLight.ts +103 -11
  125. package/src/client/engine/render/lookRender.ts +105 -0
  126. package/src/client/engine/saves/indexed.ts +2 -2
  127. package/src/client/engine/telemetry/browserErrors.ts +24 -3
  128. package/src/client/engine/telemetry/staleBuildReport.ts +22 -1
  129. package/src/client/engine/ui/debugOptions.ts +1 -1
  130. package/src/client/engine/ui/lookLightOption.ts +10 -6
  131. package/src/client/engine/ui/namePrompt.ts +7 -0
  132. package/src/client/game/boot/audio.generated.ts +114 -114
  133. package/src/client/game/boot/bytes.generated.ts +118 -220
  134. package/src/client/game/boot/placedSpawn.ts +35 -0
  135. package/src/client/game/boot/spawnDownload.ts +25 -6
  136. package/src/client/game/boot/versions.generated.ts +7 -5
  137. package/src/client/game/devScene/hook.ts +291 -0
  138. package/src/client/game/grid/cellLoading.ts +12 -2
  139. package/src/client/game/grid/live.ts +112 -16
  140. package/src/client/game/grid/liveSession.ts +33 -2
  141. package/src/client/game/grid/mapAtlas.ts +18 -4
  142. package/src/client/game/grid/minimapBlend.ts +15 -5
  143. package/src/client/game/grid/oneWayIn.ts +5 -1
  144. package/src/client/game/grid/placedCells.ts +114 -12
  145. package/src/client/game/grid/placedContent.ts +85 -0
  146. package/src/client/game/grid/prefetch.ts +9 -1
  147. package/src/client/game/grid/productInputs.ts +3 -1
  148. package/src/client/game/grid/productLeases.ts +4 -1
  149. package/src/client/game/grid/products.ts +8 -4
  150. package/src/client/game/grid/roadLook.ts +24 -15
  151. package/src/client/game/grid/roadLookPlatform.ts +4 -2
  152. package/src/client/game/grid/roadResources.ts +24 -0
  153. package/src/client/game/grid/roadSign.worker.ts +4 -3
  154. package/src/client/game/grid/roadSignPaint.ts +16 -5
  155. package/src/client/game/grid/roadSignPreparation.ts +4 -3
  156. package/src/client/game/grid/roadSignScale.ts +8 -0
  157. package/src/client/game/grid/roadTileCapture.worker.ts +3 -1
  158. package/src/client/game/grid/roadTileCaptureWorker.ts +2 -1
  159. package/src/client/game/grid/roadTileWrite.worker.ts +4 -2
  160. package/src/client/game/grid/roadTileWriter.ts +2 -1
  161. package/src/client/game/grid/screenReports.ts +39 -0
  162. package/src/client/game/grid/session.ts +20 -4
  163. package/src/client/game/grid/softWallLook.ts +25 -8
  164. package/src/client/game/mainMenu.ts +6 -2
  165. package/src/client/game/plugin/context.ts +2 -1
  166. package/src/client/game/plugin/followedMovers.ts +7 -1
  167. package/src/client/game/quest/figures.ts +2 -0
  168. package/src/client/game/session/finish.ts +6 -0
  169. package/src/client/game/shardfile/assetCache.ts +4 -4
  170. package/src/client/game/shardfile/client.ts +4 -1
  171. package/src/client/game/shardfile/clientAssets.ts +9 -5
  172. package/src/client/game/shardfile/clientLibrary.ts +1 -1
  173. package/src/client/game/shardfile/clientWater.ts +51 -9
  174. package/src/client/game/shardfile/clientWorker.ts +19 -7
  175. package/src/client/game/shardfile/look.ts +8 -3
  176. package/src/client/game/shardfile/product.ts +34 -7
  177. package/src/client/game/shardfile/productChecks.ts +2 -2
  178. package/src/client/game/shardfile/productCost.ts +2 -2
  179. package/src/client/game/shardfile/readAsset.ts +2 -2
  180. package/src/client/game/shardfile/reflectingWater.ts +73 -0
  181. package/src/client/game/shardfile/seatGrace.ts +9 -0
  182. package/src/client/game/shardfile/skinPlayback.ts +1 -1
  183. package/src/client/game/systems/npc/figureRows.ts +9 -0
  184. package/src/client/host/online/doctor.ts +2 -0
  185. package/src/client/host/online/linkScreens.ts +30 -4
  186. package/src/client/host/standalone/shell.ts +4 -0
  187. package/src/cook/game/astc6Encode.ts +55 -0
  188. package/src/cook/game/astc6Wasm.ts +176 -0
  189. package/src/cook/game/cookJob.ts +30 -6
  190. package/src/cook/game/cookWorker.ts +38 -11
  191. package/src/cook/game/entryTotals.ts +51 -24
  192. package/src/cook/game/shardCook.ts +35 -7
  193. package/src/cook/game/spawnParts.ts +33 -8
  194. package/src/cook/game/tierTextures.ts +87 -14
  195. package/src/server/engine/ai/bossContenders.ts +27 -3
  196. package/src/server/engine/ai/phases.ts +1 -1
  197. package/src/server/engine/entities/creatureRefill.ts +9 -2
  198. package/src/server/engine/net/ledgerBook.ts +2 -0
  199. package/src/server/engine/net/room.ts +15 -0
  200. package/src/server/engine/sim/respawn.ts +8 -0
  201. package/src/server/game/boss/arenaRoomEntry.ts +5 -1
  202. package/src/server/game/boss/arenaRoomNative.ts +2 -0
  203. package/src/server/game/boss/native.ts +2 -1
  204. package/src/server/game/boss/nativeWake.ts +9 -5
  205. package/src/server/game/boss/openArenaNative.ts +2 -2
  206. package/src/server/game/boss/openArenaRoom.ts +3 -1
  207. package/src/server/game/grid/room.ts +44 -3
  208. package/src/server/game/grid/simulation.ts +23 -0
  209. package/src/server/game/population/mixedRoster.ts +11 -3
  210. package/src/server/game/population/nativeBake.ts +8 -3
  211. package/src/server/game/population/nativeReturns.ts +6 -3
  212. package/src/server/game/population/roster.ts +5 -3
  213. package/src/server/game/quest/eliteDrops.ts +15 -4
  214. package/src/server/game/quest/nativeChapter.ts +1 -1
  215. package/src/server/game/quest/nativeComposition.ts +5 -1
  216. package/src/server/game/riding/nativeTaming.ts +10 -6
  217. package/src/server/game/riding/wildRefill.ts +3 -2
  218. package/src/server/game/shardfile/bossRow.ts +4 -2
  219. package/src/server/game/shardfile/homeKeeper.ts +4 -2
  220. package/src/server/host/bake/headlessWorker.ts +1 -1
  221. package/src/server/host/dedicated/cellHost.ts +98 -16
  222. package/src/server/host/dedicated/cellProtocol.ts +16 -1
  223. package/src/server/host/dedicated/cellWorker.ts +8 -5
  224. package/src/server/host/dedicated/dedicatedRoom.ts +16 -6
  225. package/src/server/host/dedicated/gridCells.ts +15 -6
  226. package/src/server/host/dedicated/loopLag.ts +21 -0
  227. package/src/server/host/dedicated/main.ts +13 -5
  228. package/src/server/host/dedicated/packReader.ts +3 -3
  229. package/src/server/host/dedicated/placementFile.ts +3 -2
  230. package/src/server/host/dedicated/roadRoom.ts +34 -4
  231. package/src/server/host/dedicated/serverMetrics.ts +126 -0
  232. package/src/server/host/dedicated/socketPump.ts +21 -4
  233. package/src/server/host/dedicated/workerTable.ts +15 -4
  234. package/src/server/host/dedicated/world.ts +65 -7
  235. package/src/server/host/headless.ts +1 -1
  236. package/src/server/host/headlessRuntime.ts +1 -1
  237. package/src/server/host/standalone/roadWorld.ts +15 -3
  238. package/src/server/host/standalone/serverHost.ts +4 -1
  239. package/src/server/host/standalone/serverProduct.ts +41 -11
  240. package/src/shared/engine/ai/BossBrain.ts +8 -0
  241. package/src/shared/game/boss/wake.ts +6 -0
  242. package/src/shared/game/devColliders.ts +47 -0
  243. package/src/shared/game/eliteSystem.ts +8 -0
  244. package/src/shared/game/grid/allocator.ts +3 -0
  245. package/src/shared/game/grid/placementRows.ts +5 -2
  246. package/src/shared/game/plugin/bossRecord.ts +3 -2
  247. package/src/shared/game/shardfile/ktx2Targets.ts +23 -3
  248. package/src/shared/game/shardfile/outputDescriptor.ts +9 -5
  249. package/src/shared/game/shardfile/packReads.ts +28 -3
  250. package/src/shared/game/shardfile/serverPack.ts +9 -0
  251. package/src/shared/game/systems/looks/trampleField.ts +2 -0
  252. package/src/shared/host/formatJsonSchema.ts +2 -2
  253. package/src/tsconfig.json +1 -27
  254. package/lint/host-reviews.json +0 -14
  255. package/lint/listed-view-code.json +0 -13
  256. package/lint/platform-pending-users.json +0 -2520
  257. package/lint/platform-pending-users.md +0 -18
  258. package/scripts/cell-mem/metrics-preload.mjs +0 -65
  259. package/scripts/check-closed-components.d.mts +0 -7
  260. package/scripts/check-closed-components.mjs +0 -87
  261. package/scripts/g571-hosts.d.mts +0 -3
  262. package/scripts/g571-hosts.mjs +0 -54
  263. package/scripts/host-ruler/register-migrate.mjs +0 -242
  264. package/scripts/listed-view-code.d.mts +0 -7
  265. package/scripts/listed-view-code.mjs +0 -93
  266. package/scripts/look-loop/fit-lut.py +0 -142
  267. package/scripts/look-loop/palette-delta.py +0 -183
  268. package/scripts/look-loop/regions/driftwood-isle.json +0 -25
  269. package/scripts/look-loop/regions/far-reach.json +0 -225
  270. package/scripts/look-loop/regions/open-plot-night-market.json +0 -855
  271. package/scripts/look-loop/regions/pine-hollow.json +0 -22
  272. package/scripts/look-loop/regions/sunscar-dunes.json +0 -281
  273. package/scripts/platform-chargebacks.d.mts +0 -9
  274. package/scripts/platform-chargebacks.mjs +0 -135
  275. package/scripts/shard-component-spans.d.mts +0 -15
  276. package/scripts/shard-component-spans.mjs +0 -18
  277. package/scripts/shard-components.d.mts +0 -16
  278. package/scripts/shard-components.mjs +0 -363
  279. package/scripts/shard-platform-hosts.d.mts +0 -2
  280. package/scripts/shard-platform-hosts.mjs +0 -93
  281. package/scripts/shard-platform-sections.d.mts +0 -2
  282. package/scripts/shard-platform-sections.mjs +0 -9
  283. package/scripts/shard-platform.d.mts +0 -76
  284. package/scripts/shard-platform.mjs +0 -1072
  285. package/src/.oxfmtrc.json +0 -48
  286. package/src/scripts/ask-new.sh +0 -29
  287. package/src/scripts/asks.mjs +0 -142
  288. package/src/scripts/herdr-prompt.sh +0 -34
  289. package/src/scripts/herdr-question-open.sh +0 -67
  290. package/src/scripts/md-wrap.mjs +0 -229
  291. /package/scripts/{shard-platform-format.d.mts → node-format.d.mts} +0 -0
  292. /package/scripts/{shard-platform-format.mjs → node-format.mjs} +0 -0
  293. /package/scripts/{shard-platform-output.d.mts → output-reader.d.mts} +0 -0
@@ -1,1072 +0,0 @@
1
- #!/usr/bin/env node
2
- // G291: authored runtime TS / the frozen legacy TS size; G604: a shard passes only at zero.
3
- // G417: one measure only; platform-native shards have no frozen denominator.
4
- import { representativeProduct, shardProducts } from './shard-outputs.mjs';
5
- import { productManifestPath } from './authored-manifest.mjs';
6
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
7
- import { createHash } from 'node:crypto';
8
- import { relative, resolve } from 'node:path';
9
- import { pathToFileURL } from 'node:url';
10
- import { parseSync } from 'vite';
11
- import * as v from 'valibot';
12
- import { resolveSpecifier } from './check-graph.mjs';
13
- import { g571HostApprovals, approvedG571Host } from './g571-hosts.mjs';
14
- import { declarationConfigProgram } from '../lint/declaration-config.mjs';
15
- import { shardLineBaselines } from './decision-legacy-lines.mjs';
16
- import { componentInventory, COMPONENT_SHARDS, SHARD_WAVES } from './shard-components.mjs';
17
- import { loadListedViews, listedViewInventory } from './listed-view-code.mjs';
18
- import { createOutputReader } from './shard-platform-output.mjs';
19
- import { sectionHostImports } from './shard-platform-hosts.mjs';
20
- import { runtimeClosures } from './shard-runtime-closure.mjs';
21
- import { chargePlatformUsers, hasChargebackDeclarations, inlinePlatformPaths, inlinePlatformSpans, platformChargeback, recordPrivateCharge, retiredPlatformModule } from './platform-chargebacks.mjs';
22
- import { onDisk } from './format-package.mjs';
23
-
24
- // The compiler's declarations globally replace Array.at's optional return with T. Load its JS API
25
- // behind a checked local contract, as compile-script.mjs does, so host JS keeps native Node types.
26
- /** @typedef {{comments?: unknown, diagnostics: unknown[], sources: {statements: {kind:number,path?:{value:string}|null}[]}[], onComment: ((kind:number,text:string,range:{start:number,end:number})=>void)|null, parseFile:(source:string,path:string,entry:boolean)=>void}} AssemblyParser */
27
- /** @typedef {{Parser:new()=>AssemblyParser,NodeKind:{Import:number,Export:number}}} AssemblyApi */
28
- /** @param {unknown} value @returns {value is AssemblyApi} */
29
- function isAssemblyApi(value) {
30
- return typeof value === 'object' && value !== null && 'Parser' in value && typeof value.Parser === 'function'
31
- && 'NodeKind' in value && typeof value.NodeKind === 'object' && value.NodeKind !== null
32
- && 'Import' in value.NodeKind && typeof value.NodeKind.Import === 'number'
33
- && 'Export' in value.NodeKind && typeof value.NodeKind.Export === 'number';
34
- }
35
- const compilerSpecifier = ['assembly', 'script'].join('');
36
- /** @type {unknown} */
37
- const compiler = await import(compilerSpecifier);
38
- if (!isAssemblyApi(compiler)) throw new Error('AssemblyScript parser API unavailable');
39
- const { Parser, NodeKind } = compiler;
40
-
41
- const ROOT = resolve(import.meta.dirname, '..');
42
- const LIST = 'lint/shard-platform.json';
43
- const sourceFile = /\.(?:tsx?|as|glsl|json)$/u;
44
- const producerPath = v.pipe(v.string(), v.check(path => path.length > 0 && !path.startsWith('/') && !path.includes('\\')
45
- && path.split('/').every(part => part !== '' && part !== '.' && part !== '..')));
46
- const SourceOutputs = v.strictObject({ schema: v.literal('source-generation-outputs/1'),
47
- producers: v.record(producerPath, v.array(producerPath)) });
48
- // G291/G294's classification table. Audit findings adjust these rules explicitly, never hidden import heuristics.
49
- // Unit on BOTH sides: nonblank physical lines after parser comment removal, in .ts/.tsx only;
50
- // .as, .d.ts and tests do not enter the TS ratio. A built product ships no runtime TS (LD10 retired the
51
- // copied-runtime measurement), so the output basis counts its section hosts and private bytes only.
52
- // Authoring directories have no numerator exemption rules: they are not inputs.
53
- // The registered frozen denominator pins historical per-file counts and producer exclusions.
54
- // G294 adds one-user platform modules to the numerator; relocating a helper into engine/game/SDK cannot reduce it.
55
- // G456 H2: SDK bake modules and project validation are build tools, never shard runtime debt.
56
- // This exact path exception does not exempt SDK runtime modules or their dependencies.
57
- // G294 per export (sp-o53): users are counted per top-level declaration, not only per file, so a one-shard export moved
58
- // into an already shared file still counts. A file one shard reaches counts whole (unchanged, dead code included). In a
59
- // file two or more shards reach, each top-level declaration (export or helper; type declarations too) that exactly one
60
- // shard reaches counts its own span: nonblank lines after parser comment removal (the codeLines unit), each line once.
61
- // Its users are the shards whose own files import it, directly or through declarations of other engine/game/SDK/commons
62
- // modules they reach. Where the reading is ambiguous the rule picks the one that never hides a real use:
63
- // - names match top-level bindings lexically (no scope analysis): a local that shadows one still counts as a use;
64
- // - literal members and destructuring of an awaited import reach those exports; escaping namespaces, import
65
- // promises, `require()` and unqualified `import('x')` types conservatively reach every export;
66
- // - a shard's runtime roots and their local dependencies are used in full; build-only folders supply no users;
67
- // - evaluating a module runs its non-declaration top-level statements, so what they reference is used by every shard
68
- // that reaches the file; a variable initialiser belongs to its binding. Import lines and top-level statements of a
69
- // shared file stay shared, and a declaration no shard reaches counts for no shard.
70
- // The frozen denominator attributes no platform code (only the sealed legacy files), so no per-export rule applies there.
71
- const RULES = {
72
- typescript: /\.tsx?$/u,
73
- tests: /(?:^|\/)(?:tests?|__tests__)(?:\/|$)|\.(?:test|spec)\.tsx?$/u,
74
- attributedLayers: /^src\/(?:engine|game|sdk|sharddev)\//u,
75
- buildOnlySdk: /^src\/sharddev\/(?:bake\/|project\.ts$)/u,
76
- publicUserCount: 2,
77
- template: '_template',
78
- enforcement: 'report-only',
79
- };
80
- // AssemblyScript permits function decorators that TypeScript parsers stop at. Use its own parser.
81
- function assembly(source, path) {
82
- const parser = new Parser(), comments = new Map();
83
- parser.onComment = (_kind, _text, range) => { comments.set(range.start, { start: range.start, end: range.end }); };
84
- parser.parseFile(source, path.replace(/\.as$/u, '.ts'), true);
85
- if (parser.diagnostics.length > 0 || parser.sources.length !== 1) throw new Error(`Cannot measure invalid AssemblyScript: ${path}`);
86
- return { comments: [...comments.values()].sort((a, b) => a.start - b.start), statements: parser.sources[0].statements };
87
- }
88
-
89
- /** Parser comment spans preserve strings, regexes and template literals containing comment-looking text. */
90
- export function codeLines(source, path = 'measure.ts') {
91
- const comments = path.endsWith('.as') ? assembly(source, path).comments : parseSync(path, source).comments;
92
- return linesWithoutComments(source, comments);
93
- }
94
- function linesWithoutComments(source, comments) {
95
- const chunks = [];
96
- let cursor = 0;
97
- for (const { start, end } of comments) {
98
- chunks.push(source.slice(cursor, start), source.slice(start, end).replaceAll(/[^\n]/gu, ' '));
99
- cursor = end;
100
- }
101
- chunks.push(source.slice(cursor));
102
- return chunks.join('').split('\n').filter((line) => line.trim()).length;
103
- }
104
- /** Count raw GLSL statements without blank/comment padding, preserving quoted preprocessor paths. */
105
- export function shaderCodeLines(source) {
106
- return source.replaceAll(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\/\*[\s\S]*?\*\/|\/\/[^\n]*/gu, value =>
107
- value.startsWith('/') ? value.replaceAll(/[^\n]/gu, ' ') : value).split('\n').filter(line => line.trim()).length;
108
- }
109
- /** Raw shader source remains custom even inside a data/generator TS file; SF59 graph nodes are ordinary data. */
110
- /** @param {string} source @param {string} path @param {unknown} [program] the file's own parse of `source`, reused when given */
111
- export function rawShaderLines(source, path, program) {
112
- if (path.endsWith('.glsl')) return shaderCodeLines(source);
113
- // G480: JSON is a container, never an exemption for executable source.
114
- // Decode strings first, so escaped newlines use the same unit as .ts/.glsl.
115
- if (path.endsWith('.json')) {
116
- const visit = (value, name = '') => {
117
- if (Array.isArray(value)) return value.reduce((sum, child) => sum + visit(child, name), 0);
118
- if (value !== null && typeof value === 'object') return Object.entries(value)
119
- .reduce((sum, [key, child]) => sum + visit(child, key), 0);
120
- if (typeof value !== 'string') return 0;
121
- if (shaderText(value, name)) return shaderCodeLines(value);
122
- const expressionField = /^(?:code|script|expression|javascript|typescript|callback)$/iu.test(name);
123
- if (!/[;{}=]/u.test(value) && !expressionField && !(name === 'source' && /[()]/u.test(value))) return 0;
124
- const wrapped = `function embedded() {\n${value}\n}`;
125
- const parsed = parseSync('embedded.ts', wrapped);
126
- if (parsed.errors.length > 0) return 0;
127
- const executable = node => {
128
- if (node === null || typeof node !== 'object') return false;
129
- if (/^(?:Variable|Function|Class)Declaration$|^(?:Return|Throw|If|For|ForIn|ForOf|While|DoWhile|Switch|Try)Statement$|^(?:ArrowFunction|Function|Assignment|Update|Call|New)Expression$/u.test(node.type)) return true;
130
- if (expressionField
131
- && /^(?:Binary|Logical|Conditional|Await|Unary)Expression$/u.test(node.type)) return true;
132
- return Object.values(node).some(child => Array.isArray(child) ? child.some(executable) : executable(child));
133
- };
134
- return executable(parsed.program.body[0].body) ? linesWithoutComments(wrapped, parsed.comments) - 2 : 0;
135
- };
136
- return visit(JSON.parse(source));
137
- }
138
- if (!RULES.typescript.test(path)) return 0;
139
- let total = 0;
140
- const visit = (node, inheritedName = '') => {
141
- let name = inheritedName;
142
- if (node === null || typeof node !== 'object') return;
143
- if (node.type === 'Property') name = node.key?.name ?? node.key?.value ?? name;
144
- if (node.type === 'VariableDeclarator') name = node.id?.name ?? name;
145
- const value = node.type === 'TemplateLiteral' ? node.quasis.map(part => part.value.raw).join('\n')
146
- : node.type === 'Literal' && typeof node.value === 'string' ? node.value : null;
147
- if (value !== null && (shaderText(value, name)
148
- || /\/\*\s*glsl\s*\*\/\s*$/u.test(source.slice(Math.max(0, node.start - 24), node.start)))) {
149
- total += shaderCodeLines(value);
150
- return;
151
- }
152
- for (const child of Object.values(node)) if (Array.isArray(child)) child.forEach(part => { visit(part, name); }); else visit(child, name);
153
- };
154
- visit(program ?? parseSync(path, source).program);
155
- return total;
156
- }
157
- function shaderText(value, name) {
158
- return /\b(?:uniform|varying|attribute|precision)\s+|\b(?:vec[234]|mat[234]|sampler2D)\s+\w+|\bvoid\s+main\s*\(|#include\s*</u.test(value)
159
- || /\b(?:float|int|uint|bool)\s+\w+\s*[=;(]/u.test(value)
160
- || (/glsl|shader|^vertex|^fragment/iu.test(name) && /[;{}]/u.test(value));
161
- }
162
- // G571/G573: JSON module contracts erase completely. The unusual suffix is
163
- // not enough: executable statements under that name remain custom code.
164
- export function jsonTypeContract(source, path) {
165
- if (!path.endsWith('.d.json.ts')) return false;
166
- const program = parseSync(path, source).program;
167
- const declared = new Set(program.body.flatMap(row => row.type === 'VariableDeclaration' && row.declare
168
- ? row.declarations.filter(entry => entry.id.type === 'Identifier' && entry.init === null).map(entry => entry.id.name) : []));
169
- return program.body.every(row => {
170
- if (row.type === 'ImportDeclaration') return row.importKind === 'type' || row.specifiers.length > 0 && row.specifiers.every(spec => spec.importKind === 'type');
171
- if (row.type === 'TSTypeAliasDeclaration' || row.type === 'TSInterfaceDeclaration' || row.type === 'EmptyStatement') return true;
172
- if (row.type === 'VariableDeclaration') return row.declare && row.declarations.every(entry => entry.id.type === 'Identifier' && entry.init === null);
173
- if (row.type === 'ExportDefaultDeclaration') return row.declaration.type === 'Identifier' && declared.has(row.declaration.name);
174
- return row.type === 'TSExportAssignment' && row.expression.type === 'Identifier' && declared.has(row.expression.name);
175
- });
176
- }
177
- /** G392 call 36: a thin declaration entry is not custom; executable logic is. */
178
- export function declarationOnlyConfig(source, path = 'shard.config.ts') {
179
- return declarationConfigProgram(parseSync(path, source).program);
180
- }
181
-
182
- /** G423 extends call 36 to root manifest.ts only. Literal rows, const aliases, imported
183
- * values/member reads, spreads and erased TS types are declarations; referenced modules keep
184
- * their existing reach/counts. No calls (even config wrappers), mutation, functions, classes,
185
- * control flow or bare side-effect imports qualify. Unknown syntax stays custom. Raw GLSL
186
- * literals still count separately, just as they do in data/. No code is executed to classify it. */
187
- export function declarationOnlyManifest(source, path = 'manifest.ts') {
188
- const value = node => {
189
- switch (node?.type) {
190
- case 'Literal': case 'Identifier': return true;
191
- case 'ObjectExpression': return node.properties.every(property => property.type === 'SpreadElement'
192
- ? value(property.argument) : property.type === 'Property' && property.kind === 'init' && !property.method
193
- && !property.computed && value(property.value));
194
- case 'ArrayExpression': return node.elements.every(element => element === null || value(element));
195
- case 'SpreadElement': return value(node.argument);
196
- case 'MemberExpression': return !node.optional && value(node.object)
197
- && (node.computed ? node.property.type === 'Literal' : node.property.type === 'Identifier');
198
- case 'UnaryExpression': return ['-', '+'].includes(node.operator) && node.argument.type === 'Literal'
199
- && typeof node.argument.value === 'number';
200
- case 'TemplateLiteral': return node.expressions.length === 0;
201
- case 'TSAsExpression': case 'TSSatisfiesExpression': case 'TSTypeAssertion': return value(node.expression);
202
- default: return false;
203
- }
204
- };
205
- const statement = node => {
206
- switch (node.type) {
207
- case 'ImportDeclaration': return node.importKind === 'type' || node.specifiers.length > 0;
208
- case 'VariableDeclaration': return node.kind === 'const' && node.declarations.every(row =>
209
- row.id.type === 'Identifier' && row.init !== null && value(row.init));
210
- case 'ExportDefaultDeclaration': return value(node.declaration);
211
- case 'ExportNamedDeclaration': return node.source === null && (node.declaration === null || statement(node.declaration));
212
- case 'TSInterfaceDeclaration': case 'TSTypeAliasDeclaration': case 'EmptyStatement': return true;
213
- default: return false;
214
- }
215
- };
216
- return parseSync(path, source).program.body.every(statement);
217
- }
218
-
219
- /** G390: measured custom reduction contributes 80 points; tiles plus no private bytes contribute 20.
220
- * @param {number|null} customPercent @param {{status:string,tiles:{total:number}|null,privateBinaries:readonly string[]}} content
221
- * @returns {import('./shard-platform.mjs').PortHeadline} */
222
- export function portHeadline(customPercent, content) {
223
- if (customPercent !== null && (!Number.isFinite(customPercent) || customPercent < 0)) throw new Error('Invalid custom percentage');
224
- const world = content.status !== 'built' ? 'unavailable' : content.tiles?.total > 0 && content.privateBinaries.length === 0
225
- ? 'yes' : content.tiles?.total > 0 || content.privateBinaries.length === 0 ? 'partial' : 'no';
226
- const worldPoints = world === 'yes' ? 20 : world === 'partial' ? 10 : 0;
227
- return { customPercent, world, percent: world === 'unavailable' || customPercent === null ? null
228
- : 80 * Math.max(0, Math.min(1, (100 - customPercent) / 80)) + worldPoints };
229
- }
230
- const HEADLINE_SHARDS = [ 'sunscar-dunes', 'far-reach', 'nine-dragon-stack', 'nalati-grasslands', 'driftwood-isle', 'pine-hollow'];
231
- /** @param {Record<string,{port:import('./shard-platform.mjs').PortHeadline}>} rows */
232
- export function portAverage(rows) {
233
- const values = HEADLINE_SHARDS.map(slug => rows[slug]?.port.percent ?? null);
234
- return values.some(value => value === null) ? null : values.reduce((sum, value) => sum + (value ?? 0), 0) / values.length;
235
- }
236
- function filesIn(dir) {
237
- if (!existsSync(dir)) return [];
238
- return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
239
- const path = resolve(dir, entry.name);
240
- return entry.isDirectory() ? filesIn(path) : sourceFile.test(path) && !path.endsWith('.d.ts') ? [path] : [];
241
- });
242
- }
243
- function sourceInfo(source, path) {
244
- if (path.endsWith('.glsl') || path.endsWith('.json')) return { comments: [], specs: [] };
245
- if (path.endsWith('.as')) {
246
- const parsed = assembly(source, path);
247
- return { comments: parsed.comments, specs: parsed.statements
248
- .filter(node => node.kind === NodeKind.Import || node.kind === NodeKind.Export)
249
- .flatMap(node => node.path ? [node.path.value] : []) };
250
- }
251
- const tree = parseSync(path, source), specs = [];
252
- for (const row of tree.module.staticImports) specs.push(row.moduleRequest.value);
253
- for (const row of tree.module.staticExports) for (const entry of row.entries) if (entry.moduleRequest) specs.push(entry.moduleRequest.value);
254
- // Ordinary imports use the parser's module index. Walk only files with expression/import-type/CommonJS edges.
255
- if (/\b(?:import|require)(?:\s|\/\*[\s\S]*?\*\/|\/\/[^\n]*\n)*\(/u.test(source)
256
- || tree.program.body.some(node => node.type === 'TSImportEqualsDeclaration')) {
257
- const add = node => specs.push(node?.type === 'Literal' && typeof node.value === 'string' ? node.value
258
- : node?.type === 'TemplateLiteral' && node.expressions.length === 0 ? node.quasis[0].value.cooked : null);
259
- const visit = node => {
260
- if (!node || typeof node !== 'object') return;
261
- if (['TSImportType', 'ImportExpression'].includes(node.type) && node.source) add(node.source);
262
- else if (node.type === 'TSExternalModuleReference') add(node.expression);
263
- else if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'require') add(node.arguments[0]);
264
- for (const child of Object.values(node)) if (Array.isArray(child)) child.forEach(visit); else if (child && typeof child === 'object') visit(child);
265
- };
266
- visit(tree.program);
267
- }
268
- return { comments: tree.comments, specs, tree };
269
- }
270
- // G294 per export: a module's top-level bindings, what each one's declaration references, and how its exports map
271
- // onto them. `refs` holds local names, `ns\0member` for a namespace-import member, and `\0spec` (`\0spec\0name` with an
272
- // import-type qualifier) for an expression or import-type module reference; an empty member evaluates only the module.
273
- // A bare module reference reaches every export. Matching is lexical, without scope analysis.
274
- const MEMBER_KEYS = new Set(['Property', 'MethodDefinition', 'PropertyDefinition', 'AccessorProperty', 'TSPropertySignature',
275
- 'TSMethodSignature', 'TSAbstractMethodDefinition', 'TSAbstractPropertyDefinition', 'TSAbstractAccessorProperty', 'ImportAttribute']);
276
- const OWN_IDS = new Set(['FunctionDeclaration', 'FunctionExpression', 'ClassDeclaration', 'ClassExpression', 'TSInterfaceDeclaration',
277
- 'TSTypeAliasDeclaration', 'TSEnumDeclaration', 'TSModuleDeclaration']);
278
- function moduleSymbols(program) {
279
- const imports = new Map(), exports = new Map(), stars = [], bindings = new Map(), init = { refs: new Set(), spans: [] }, statics = [];
280
- const namespaces = new Set();
281
- const literal = node => node?.type === 'Literal' && typeof node.value === 'string' ? node.value
282
- : node?.type === 'TemplateLiteral' && node.expressions.length === 0 ? node.quasis[0].value.cooked : null;
283
- const nameOf = node => node?.type === 'Identifier' ? node.name : literal(node);
284
- for (const node of program.body) if (node.source && /^(?:Import|ExportNamed|ExportAll)Declaration$/u.test(node.type)) statics.push(node.source.value);
285
- for (const node of program.body) if (node.type === 'ImportDeclaration') for (const spec of node.specifiers) {
286
- const name = spec.type === 'ImportSpecifier' ? nameOf(spec.imported) : spec.type === 'ImportDefaultSpecifier' ? 'default' : '*';
287
- imports.set(spec.local.name, { spec: node.source.value, name });
288
- if (name === '*') namespaces.add(spec.local.name);
289
- } else if (node.type === 'TSImportEqualsDeclaration' && node.moduleReference.type === 'TSExternalModuleReference') {
290
- imports.set(node.id.name, { spec: literal(node.moduleReference.expression), name: '*' });
291
- statics.push(literal(node.moduleReference.expression));
292
- namespaces.add(node.id.name);
293
- }
294
- const patternNames = (node, out) => {
295
- if (!node) return out;
296
- if (node.type === 'Identifier') out.push(node.name);
297
- else if (node.type === 'ObjectPattern') for (const prop of node.properties) patternNames(prop.type === 'RestElement' ? prop.argument : prop.value, out);
298
- else if (node.type === 'ArrayPattern') for (const element of node.elements) patternNames(element, out);
299
- else if (node.type === 'RestElement') patternNames(node.argument, out);
300
- else if (node.type === 'AssignmentPattern') patternNames(node.left, out);
301
- return out;
302
- };
303
- const collect = (root, refs) => {
304
- // A local constant holding import() is a namespace too. Keep its initializer
305
- // from claiming the whole module when only named members are read. A root
306
- // binding remains conservative because another module may import that object.
307
- const dynamicNamespaces = new Map(), boundImports = new Map();
308
- // The engine retry leaf returns its loader's result unchanged. Recognize
309
- // only that named import, never an arbitrary wrapper around import().
310
- const retryBindings = new Set([...imports].filter(([, row]) => row.name === 'retried'
311
- && /(?:^|\/)engine\/boot\/retry$/u.test(row.spec)).map(([name]) => name));
312
- const shadows = new Set();
313
- const findShadows = node => {
314
- if (node === null || typeof node !== 'object') return;
315
- if (Array.isArray(node)) { node.forEach(findShadows); return; }
316
- const patterns = node.type === 'VariableDeclarator' ? [node.id] : node.params ?? [];
317
- for (const pattern of patterns) for (const name of patternNames(pattern, [])) shadows.add(name);
318
- for (const child of Object.values(node)) if (child && typeof child === 'object') findShadows(child);
319
- };
320
- findShadows(root);
321
- const resolvedValue = input => {
322
- let value = input, awaited = false;
323
- while (value) {
324
- if (value.type === 'ParenthesizedExpression' || value.type === 'AwaitExpression') {
325
- if (value.type === 'AwaitExpression') awaited = true;
326
- value = value.expression ?? value.argument;
327
- } else if (value.type === 'CallExpression' && value.callee.type === 'Identifier'
328
- && retryBindings.has(value.callee.name) && !shadows.has(value.callee.name) && value.arguments.length === 1
329
- && value.arguments[0].type === 'ArrowFunctionExpression' && value.arguments[0].params.length === 0
330
- && value.arguments[0].body.type !== 'BlockStatement') value = value.arguments[0].body;
331
- else break;
332
- }
333
- return { value, awaited };
334
- };
335
- const importedValue = input => {
336
- const { value, awaited } = resolvedValue(input);
337
- return awaited && value?.type === 'ImportExpression' ? value : null;
338
- };
339
- const bindMembers = (pattern, input) => {
340
- const { value } = resolvedValue(input);
341
- if (pattern?.type !== 'ObjectPattern' || value?.type !== 'ImportExpression' || literal(value.source) === null) return;
342
- const members = pattern.properties.map(row => row.type === 'Property'
343
- ? row.computed ? literal(row.key) : nameOf(row.key) : null);
344
- if (members.every(name => name !== null)) boundImports.set(value, members);
345
- };
346
- const findNamespaces = node => {
347
- if (node === null || typeof node !== 'object') return;
348
- if (Array.isArray(node)) { node.forEach(findNamespaces); return; }
349
- if (node.type === 'VariableDeclaration' && node.kind === 'const') for (const row of node.declarations) {
350
- const value = importedValue(row.init);
351
- const spec = value?.type === 'ImportExpression' ? literal(value.source) : null;
352
- if (row !== root && row.id.type === 'Identifier' && spec !== null) {
353
- if (!dynamicNamespaces.has(row.id.name)) dynamicNamespaces.set(row.id.name, new Set());
354
- dynamicNamespaces.get(row.id.name).add(spec); boundImports.set(value, []);
355
- }
356
- }
357
- if (node.type === 'VariableDeclarator') {
358
- bindMembers(node.id, importedValue(node.init));
359
- // Promise.all preserves literal tuple positions. Narrow each directly
360
- // destructured namespace independently; rest/unknown keys still escape.
361
- const resolved = resolvedValue(node.init), call = resolved.awaited ? resolved.value : null;
362
- if (node.id.type === 'ArrayPattern' && call?.type === 'CallExpression'
363
- && call.callee.type === 'MemberExpression' && !call.callee.computed
364
- && call.callee.object.type === 'Identifier' && call.callee.object.name === 'Promise'
365
- && !imports.has('Promise') && !shadows.has('Promise')
366
- && call.callee.property.type === 'Identifier' && call.callee.property.name === 'all'
367
- && call.arguments.length === 1 && call.arguments[0].type === 'ArrayExpression'
368
- && !call.arguments[0].elements.some(row => row?.type === 'SpreadElement')
369
- && !node.id.elements.some(row => row?.type === 'RestElement')) {
370
- for (let i = 0; i < node.id.elements.length; i++) bindMembers(node.id.elements[i], call.arguments[0].elements[i]);
371
- }
372
- }
373
- if (node.type === 'MemberExpression') {
374
- const value = importedValue(node.object);
375
- const member = node.computed ? literal(node.property) : nameOf(node.property);
376
- if (value?.type === 'ImportExpression' && literal(value.source) !== null && member !== null) boundImports.set(value, [member]);
377
- }
378
- for (const child of Object.values(node)) if (child && typeof child === 'object') findNamespaces(child);
379
- };
380
- findNamespaces(root);
381
- const namespaceRef = (name, member) => {
382
- if (namespaces.has(name)) refs.add(member === null ? name : `${name}\0${member}`);
383
- for (const spec of dynamicNamespaces.get(name) ?? []) refs.add(`\0${spec}${member === null ? '' : `\0${member}`}`);
384
- };
385
- const visit = (node, parent, key, binding) => {
386
- if (node === null || typeof node !== 'object') return;
387
- if (Array.isArray(node)) { for (const child of node) visit(child, parent, key, binding); return; }
388
- if (typeof node.type !== 'string') return;
389
- if (node.type === 'Identifier') {
390
- const skip = binding === true || (key === 'property' && parent.type === 'MemberExpression' && !parent.computed)
391
- || (key === 'key' && MEMBER_KEYS.has(parent.type) && !parent.computed) || (key === 'right' && parent.type === 'TSQualifiedName')
392
- || (key === 'label') || (key === 'id' && (parent.type === 'TSEnumMember' || OWN_IDS.has(parent.type)))
393
- || (key === 'name' && parent.type === 'TSTypeParameter');
394
- if (!skip) {
395
- if (dynamicNamespaces.has(node.name)) namespaceRef(node.name, null);
396
- else refs.add(node.name);
397
- }
398
- visit(node.typeAnnotation, node, 'typeAnnotation', false);
399
- visit(node.decorators, node, 'decorators', false);
400
- return;
401
- }
402
- if (node.type === 'JSXIdentifier') {
403
- if ((key === 'name' && /^(?:JSXOpening|JSXClosing)Element$/u.test(parent.type)) || (key === 'object' && parent.type === 'JSXMemberExpression')) refs.add(node.name);
404
- return;
405
- }
406
- // Literal member reads are narrow; passing/spreading the object or an
407
- // unknown computed key still reaches every export through the identifier.
408
- if (node.type === 'MemberExpression' && node.object.type === 'Identifier'
409
- && (namespaces.has(node.object.name) || dynamicNamespaces.has(node.object.name))) {
410
- const member = node.computed ? literal(node.property) : nameOf(node.property);
411
- if (member !== null) { namespaceRef(node.object.name, member); return; }
412
- }
413
- if (node.type === 'TSQualifiedName' && node.left.type === 'Identifier' && namespaces.has(node.left.name)) {
414
- namespaceRef(node.left.name, node.right.name); return;
415
- }
416
- if (node.type === 'ImportExpression' || node.type === 'TSImportType') {
417
- const spec = literal(node.source), member = node.qualifier?.type === 'Identifier' ? `\0${node.qualifier.name}` : '';
418
- if (spec !== null) {
419
- refs.add(`\0${spec}${boundImports.has(node) ? '\0' : member}`);
420
- for (const name of boundImports.get(node) ?? []) refs.add(`\0${spec}\0${name}`);
421
- }
422
- if (node.type === 'TSImportType') { visit(node.typeArguments, node, 'typeArguments', false); return; }
423
- }
424
- if (node.type === 'CallExpression' && node.callee.type === 'Identifier' && node.callee.name === 'require') { const spec = literal(node.arguments[0]); if (spec !== null) refs.add(`\0${spec}`); }
425
- for (const [childKey, child] of Object.entries(node)) {
426
- if (childKey === 'type' || childKey === 'start' || childKey === 'end' || childKey === 'range') continue;
427
- // Binding positions are not references; their defaults, computed keys and type annotations are.
428
- const childBinding = (childKey === 'id' && node.type === 'VariableDeclarator') || (childKey === 'params' && /Function|Arrow|TSMethodSignature|TSCallSignature|TSConstructSignature|TSFunctionType|TSConstructorType|TSDeclareFunction/u.test(node.type))
429
- || (childKey === 'param' && node.type === 'CatchClause') || (childKey === 'parameter' && node.type === 'TSParameterProperty')
430
- || (binding && ((node.type === 'Property' && childKey === 'value') || (node.type === 'RestElement' && childKey === 'argument')
431
- || (node.type === 'AssignmentPattern' && childKey === 'left') || (node.type === 'ArrayPattern' && childKey === 'elements')
432
- || (node.type === 'ObjectPattern' && childKey === 'properties')));
433
- visit(child, node, childKey, childBinding);
434
- }
435
- };
436
- visit(root, null, null, false);
437
- };
438
- const bind = (name, span, declaration) => {
439
- if (!bindings.has(name)) bindings.set(name, { spans: [], refs: new Set() });
440
- const row = bindings.get(name);
441
- row.spans.push(span);
442
- collect(declaration, row.refs);
443
- };
444
- const declare = (declaration, statement) => {
445
- const span = { start: statement.start, end: statement.end };
446
- if (declaration.type === 'VariableDeclaration') {
447
- for (const declarator of declaration.declarations) {
448
- const names = patternNames(declarator.id, []), own = declaration.declarations.length === 1 ? span : { start: declarator.start, end: declarator.end };
449
- for (const name of names) bind(name, own, declarator);
450
- }
451
- return declaration.declarations.flatMap(row => patternNames(row.id, []));
452
- }
453
- if (declaration.type === 'TSModuleDeclaration' && (declaration.id?.type !== 'Identifier' || declaration.kind === 'global')) { collect(declaration, init.refs); init.spans.push(span); return []; }
454
- if (declaration.type === 'TSImportEqualsDeclaration') { if (!imports.has(declaration.id.name)) bind(declaration.id.name, span, declaration.moduleReference); return [declaration.id.name]; }
455
- if (declaration.id?.type === 'Identifier') { bind(declaration.id.name, span, declaration); return [declaration.id.name]; }
456
- return null;
457
- };
458
- for (const node of program.body) {
459
- if (node.type === 'ImportDeclaration' || (node.type === 'TSImportEqualsDeclaration' && imports.has(node.id.name))) continue;
460
- if (node.type === 'ExportAllDeclaration') {
461
- if (node.exported === null) stars.push(node.source.value);
462
- else exports.set(nameOf(node.exported), { spec: node.source.value, name: '*' });
463
- continue;
464
- }
465
- if (node.type === 'ExportNamedDeclaration') {
466
- if (node.declaration) for (const name of declare(node.declaration, node) ?? []) exports.set(name, { local: name });
467
- for (const spec of node.specifiers) exports.set(nameOf(spec.exported), node.source ? { spec: node.source.value, name: nameOf(spec.local) } : { local: nameOf(spec.local) });
468
- continue;
469
- }
470
- if (node.type === 'ExportDefaultDeclaration') {
471
- const names = /Declaration$|^TSDeclareFunction$/u.test(node.declaration.type) ? declare(node.declaration, node) : null;
472
- if (names?.length === 1) exports.set('default', { local: names[0] });
473
- else { bind('\0default', { start: node.start, end: node.end }, node.declaration); exports.set('default', { local: '\0default' }); }
474
- continue;
475
- }
476
- if (node.type === 'TSExportAssignment') { bind('\0default', { start: node.start, end: node.end }, node.expression); exports.set('default', { local: '\0default' }); continue; }
477
- const names = /Declaration$|^TSDeclareFunction$/u.test(node.type) ? declare(node, node) : null;
478
- if (names === null) { collect(node, init.refs); init.spans.push({ start: node.start, end: node.end }); }
479
- }
480
- return { imports, exports, stars, bindings, init, statics };
481
- }
482
- /** Per line of `source`: does it hold code once parser comment spans are blanked (the codeLines unit)? */
483
- function codeLineMask(source, comments) {
484
- const chunks = [];
485
- let cursor = 0;
486
- for (const { start, end } of comments) {
487
- chunks.push(source.slice(cursor, start), source.slice(start, end).replaceAll(/[^\n]/gu, ' '));
488
- cursor = end;
489
- }
490
- chunks.push(source.slice(cursor));
491
- const starts = [0], blanked = chunks.join('');
492
- for (let index = 0; index < blanked.length; index++) if (blanked[index] === '\n') starts.push(index + 1);
493
- const code = blanked.split('\n').map(line => line.trim() !== '');
494
- const lineOf = offset => { let low = 0, high = starts.length - 1; while (low < high) { const mid = (low + high + 1) >> 1; if (starts[mid] <= offset) low = mid; else high = mid - 1; } return low; };
495
- return { code, lineOf };
496
- }
497
- // Cache only syntax-derived facts. Package resolution, user attribution and every gate still run on this tree.
498
- function cachedSourceInfo(source, path, directory, recipe) {
499
- const hash = value => createHash('sha256').update(value).digest('hex');
500
- const key = hash(`${recipe}\0${path}\0${source}`), file = resolve(directory, `${key}.json`);
501
- const revive = (_key, value) => value !== null && typeof value === 'object' && Object.hasOwn(value, '$map') ? new Map(value.$map)
502
- : value !== null && typeof value === 'object' && Object.hasOwn(value, '$set') ? new Set(value.$set) : value;
503
- try {
504
- const stored = JSON.parse(readFileSync(file, 'utf8'));
505
- if (typeof stored.payload === 'string' && hash(stored.payload) === stored.hash) return JSON.parse(stored.payload, revive);
506
- } catch (error) {
507
- if (!(error instanceof Error && ('code' in error && error.code === 'ENOENT' || error instanceof SyntaxError))) throw error;
508
- }
509
- const parsed = sourceInfo(source, path);
510
- const facts = { comments: parsed.comments, specs: parsed.specs, shaderLines: rawShaderLines(source, path, parsed.tree?.program),
511
- symbols: parsed.tree === undefined ? undefined : moduleSymbols(parsed.tree.program) };
512
- const payload = JSON.stringify(facts, (_key, value) => value instanceof Map ? { $map: [...value] }
513
- : value instanceof Set ? { $set: [...value] } : value);
514
- mkdirSync(directory, { recursive: true });
515
- const temporary = `${file}.${process.pid}.tmp`;
516
- writeFileSync(temporary, JSON.stringify({ hash: hash(payload), payload }));
517
- renameSync(temporary, file);
518
- return facts;
519
- }
520
-
521
- // G473-G477 approvals are explicit feature receipts, separate from G441's
522
- // temporary credit for the current/completed wave. A wave change cannot revoke
523
- // these platform approvals, and an ordinary pending row cannot claim one.
524
- /** @type {Record<string,string>} */
525
- const approvedFeatures = {
526
- 'grass-field':'G478',
527
- 'audio-cue-director':'G478',
528
- 'stealth-and-detection':'G478',
529
- 'mounts-riding-taming':'G478',
530
- 'grapple-traversal':'G478',
531
- 'walk-in-portal-ride':'G478',
532
- 'practice-courses':'G478',
533
- 'H6 ambient life':'G474',
534
- 'light emitters':'G478',
535
- 'eased fields':'G484',
536
- 'declared runtime entry':'G483',
537
- 'contracts + elites':'G473',
538
- 'world scene assembly':'G483',
539
- 'boss fight host':'G474',
540
- 'living-buildings':'G474',
541
- 'weather reactions + keyed sky':'G474', 'quadruped-rig':'G474', 'actor-spawn':'G474',
542
- 'bolt-flight':'G474', 'quest-step-runner':'G474', 'loadout':'G474',
543
- 'streamed-cover':'G475', 'streamed cover':'G475', 'toon look host':'G475', 'painterly look host':'G478', 'collections':'G475', 'held-arms':'G475',
544
- 'water-ripples':'G474', 'colour-ramp-fog':'G475',
545
- 'low-poly-binder':'G475', 'resident-world':'G475',
546
- };
547
- /** @param {import('./shard-platform.mjs').PendingPlatformUser} entry */
548
- function approvedFeature(entry) {
549
- const approval=entry.approvedFeature;
550
- return approval!==undefined && approvedFeatures[approval.name]===approval.decision.row;
551
- }
552
- // G419: planned users are an explicit, temporary allowance, never actual import-graph users.
553
- const PendingUsers = v.strictObject({ schema:v.literal('platform-pending-users/1'), entries:v.pipe(v.array(v.strictObject({
554
- module:v.pipe(producerPath,v.regex(/^src\/(?:engine|game|sdk|sharddev|format)\//u)), export:v.optional(v.string()),
555
- shard:v.exactOptional(v.picklist(['driftwood-isle','pine-hollow','nalati-grasslands','nine-dragon-stack'])),
556
- plan:v.exactOptional(v.strictObject({path:v.pipe(producerPath,v.regex(/^docs\/plans\//u)),row:v.string()})),
557
- documentation:v.pipe(producerPath,v.regex(/^docs\//u)), 'rechecked-by':v.exactOptional(v.literal('end of W3')),
558
- approvedFeature:v.exactOptional(v.strictObject({name:v.string(),decision:v.strictObject({path:v.literal('docs/plans/decisions.md'),row:v.picklist(['G473','G474','G475','G478','G483','G484'])})})),
559
- })), v.check(rows => rows.every(entry => {
560
- const complete = entry.shard !== undefined && entry.plan !== undefined && entry['rechecked-by'] !== undefined;
561
- const empty = entry.shard === undefined && entry.plan === undefined && entry['rechecked-by'] === undefined;
562
- return complete || (empty && entry.approvedFeature !== undefined);
563
- }), 'A pending user needs its shard, plan and recheck; an approved feature needs only its decision')) });
564
- const unsortedDoc=text=>text.replaceAll(/\b(engine|game)\/(?:client|server|shared|cook)\//gu,'$1/');
565
- /** Read documented general hosts backed by a real future user or an explicit day-one approval.
566
- * @param {string} root @returns {import('./shard-platform.mjs').PendingPlatformUser[]} */
567
- export function pendingPlatformUsers(root) {
568
- return readPendingPlatformUsers(root,(path,source)=>moduleSymbols(parseSync(path,source).program));
569
- }
570
- function readPendingPlatformUsers(root,symbolsFor) {
571
- const file=resolve(root,'lint/platform-pending-users.json');
572
- if(!existsSync(file))return [];
573
- const entries=v.parse(PendingUsers,JSON.parse(readFileSync(file,'utf8'))).entries
574
- .filter(entry => !retiredPlatformModule(entry.module) || existsSync(onDisk(root,entry.module)));
575
- const seen=new Set();
576
- const names={'driftwood-isle':'Driftwood','pine-hollow':'Pine','nalati-grasslands':'Nalati','nine-dragon-stack':'Nine'};
577
- for(const entry of entries){
578
- const key=`${entry.module}#${entry.export??'*'}:${entry.shard??'approved'}`;
579
- if(seen.has(key))throw new Error(`Duplicate pending platform user: ${key}`);seen.add(key);
580
- if(entry.approvedFeature!==undefined){
581
- if(!approvedFeature(entry))throw new Error(`Unapproved platform feature: ${key}`);
582
- const decision=entry.approvedFeature.decision;
583
- if(!readFileSync(resolve(root,decision.path),'utf8').split('\n').some(line=>line.split('|')[1]?.trim()===decision.row))
584
- throw new Error(`Missing platform feature decision: ${key}`);
585
- }
586
- const source=readFileSync(onDisk(root,entry.module),'utf8');
587
- if(/src\/shards\/|@wildshard\/shards\/|sunscar-dunes|far-reach|driftwood-isle|pine-hollow|nalati-grasslands|nine-dragon-stack/u.test(source))
588
- throw new Error(`Pending feature names a shard: ${entry.module}`);
589
- const symbols=symbolsFor(entry.module,source);
590
- if(entry.export!==undefined&&!symbols.exports.has(entry.export))throw new Error(`Missing pending platform export: ${key}`);
591
- // A retag moves the file between sides and leaves the doc's row true, so both are read without their side (J122).
592
- const documentation=unsortedDoc(readFileSync(resolve(root,entry.documentation),'utf8'));
593
- if(!documentation.includes(unsortedDoc(entry.module.replace(/^src\//u,'').replace(/\.ts$/u,''))))
594
- throw new Error(`Pending feature lacks documentation: ${key}`);
595
- if (entry.plan !== undefined && entry.shard !== undefined) {
596
- const row=readFileSync(resolve(root,entry.plan.path),'utf8').split('\n').find(line=>line.split('|')[1]?.trim()===entry.plan?.row);
597
- if(!row||!row.includes(names[entry.shard]))throw new Error(`Missing later-wave plan row: ${key}`);
598
- }
599
- }
600
- return entries;
601
- }
602
- /** Separate temporary planned users from the remaining sole-user charges.
603
- * @param {string} slug
604
- * @param {import('./shard-platform.mjs').PlatformModuleCharge[]} modules
605
- * @param {{path:string;name:string;exported:boolean;lines:number}[]} exports
606
- * @param {import('./shard-platform.mjs').PendingPlatformUser[]} allowances */
607
- export function partitionPendingPlatformUsers(slug,modules,exports,allowances) {
608
- /** @type {import('./shard-platform.mjs').PendingPlatformCharge[]} */
609
- const pending=[];
610
- const charged=(row)=>{
611
- if (platformChargeback(row.path, 'name' in row ? row.name : undefined) !== null) return true;
612
- const eligibleWave=SHARD_WAVES.some(wave=>(wave.current||wave.status.startsWith('closed'))&&wave.shards.some(shard=>shard.slug===slug));
613
- const matches=allowances.filter(entry=>(approvedFeature(entry)||(eligibleWave&&entry.shard!==undefined))&&entry.shard!==slug&&entry.module===row.path
614
- && (entry.export===undefined||('name' in row&&row.exported&&entry.export===row.name)));
615
- if(matches.length===0)return true;
616
- pending.push({...row,status:'pending second user',users:matches});return false;
617
- };
618
- const keptModules = modules.filter(charged);
619
- const keptExports = exports.filter(row => !keptModules.some(module => module.path === row.path)).filter(charged);
620
- // A one-user module may retain older approved code while its new declarations
621
- // charge back. Report its pending remainder once, excluding those declarations.
622
- for (const row of pending) if (!('name' in row)) row.lines -= keptExports.filter(entry => entry.path === row.path).reduce((sum, entry) => sum + entry.lines, 0);
623
- return {modules:keptModules,exports:keptExports,pending:pending.filter(row => row.lines > 0)};
624
- }
625
-
626
- // The application's real composition roots are a consumer, not a shard. Their
627
- // named reach prevents menu/travel/session code from becoming a sole-shard debt.
628
- // Keep this list short: never add content folders or shard-specific installers.
629
- const SHELL_ROOTS = ['src/client/app/entry.ts', 'src/client/game/session/session.ts', 'src/client/game/mainMenu.ts', 'src/client/game/session/loadout.ts'];
630
- const SHELL_USER = '@game-shell';
631
- // Loading a default content catalogue is not using that content in a shard.
632
- // The shell supplies a second user only for these orchestration modules and
633
- // these UI bridge declarations, never species, models, rendering or gameplay.
634
- const SHELL_CONTROL_PREFIXES = ['src/client/game/grid/', 'src/shared/game/grid/', 'src/server/game/grid/', 'src/client/game/session/', 'src/client/game/shard/', 'src/server/game/shard/', 'src/client/game/travel/'];
635
- const SHELL_UI_CONTROL = new Set([
636
- 'gridHome', 'enterGrid', 'bootPageMode', 'dropGridIntent', 'selected', 'refused', 'loop',
637
- 'safeGridRecovery', 'consumeGridRecovery', 'pageGridRecovery', 'clearGridRecovery',
638
- 'gridRecoveryRefused', 'gridRecoveryLoop', 'PageResidencyBoot', 'preparePageResidency',
639
- 'emptyShardfileSource', 'installShardfileProduct', 'selectSource', 'installManifestShardfile',
640
- 'shardfileLevelSpec', 'loadShardfile', 'configuredShardfile', 'installShardfileSource',
641
- ]);
642
- /** @param {string} path @param {string|null} [local] */
643
- const shellControl = (path, local = null) => SHELL_CONTROL_PREFIXES.some(prefix => path.startsWith(prefix))
644
- || (path === 'src/client/game/plugin/ui.ts' && (local === null || SHELL_UI_CONTROL.has(local)));
645
-
646
- // Scoped to one immutable census; no policy verdict survives another report.
647
- function censusMemo() {
648
- return {sources:new Map(),texts:new Map(),graphs:new Map(),probes:new Map(),targets:new Map(),edges:new Map(),
649
- symbols:new Map(),masks:new Map(),pending:new Map(),authored:new Map()};
650
- }
651
- /** @param {string} root @param {boolean} includeSources @param {string} products @param {string[]} slugs @param {boolean} sourceProgress @param {string} sectionProducts */
652
- function countOutput(root, includeSources, products, slugs, sourceProgress = false, sectionProducts = resolve(root,'out'), memo = censusMemo(), reader = createOutputReader(root,sourceProgress ? sectionProducts : products)) {
653
- const attributed = path => RULES.attributedLayers.test(path) || platformChargeback(path) !== null || hasChargebackDeclarations(path);
654
- const platform = path => /^src\/(?:engine|game|sdk|sharddev|commons)\//u.test(path) || attributed(path);
655
- // One measurement reads one immutable tree: memoize file probes, package targets and edges (pnpm gen, ~3 s).
656
- const {probes,targets,edges,texts,graphs,sources,masks}=memo;
657
- const exists = (path) => { let hit = probes.get(path); if (hit === undefined) { hit = existsSync(onDisk(root, path)); probes.set(path, hit); } return hit; };
658
- const counts = new Map();
659
- const baselines = shardLineBaselines(root);
660
- /** @type {Set<string>} */
661
- const generated = new Set();
662
- // Retained source tables also have exact producer/output identities; older tooling predates generation jobs.
663
- const sourceOutputs = 'scripts/source-generation-outputs.json';
664
- if (exists(sourceOutputs)) {
665
- const catalogue = v.parse(SourceOutputs, JSON.parse(readFileSync(resolve(root, sourceOutputs), 'utf8')));
666
- for (const outputs of Object.values(catalogue.producers)) for (const path of outputs) generated.add(path);
667
- }
668
- if (sourceProgress) for (const product of shardProducts(root, slugs)) {
669
- if (!exists(`src/shards/${product.folder}/manifest.json`)) continue;
670
- const path = productManifestPath(root, product);
671
- if (!exists(path)) throw new Error(`Source census requires generated discovery: ${path}; restore generation before counting`);
672
- }
673
- const text = (path) => {
674
- if (!texts.has(path)) texts.set(path, readFileSync(onDisk(root, path), 'utf8'));
675
- return texts.get(path);
676
- };
677
- // G458 alone retains the predecessor source-progress reading. It is never an
678
- // output percentage or a source fallback, and is not available to port badges.
679
- const sourceData = path => /^src\/shards\/[^/]+\/data\/.*\.tsx?$/u.test(path);
680
- const ignored = path => sourceProgress ? generated.has(path)&&!sourceData(path)
681
- : !path.startsWith(`${relative(root, products).replaceAll('\\', '/')}/`) && generated.has(path);
682
- const parseCache = process.env.WS_SHARD_PARSE_CACHE;
683
- const parseRecipe = parseCache ? createHash('sha256').update(readFileSync(import.meta.filename)).update(exists('pnpm-lock.yaml') ? text('pnpm-lock.yaml') : '').digest('hex') : '';
684
- const info = path => { if (!sources.has(path)) sources.set(path, parseCache ? cachedSourceInfo(text(path), path, parseCache, parseRecipe) : sourceInfo(text(path), path)); return sources.get(path); };
685
- const symbolsOf = path => { if (!memo.symbols.has(path)) memo.symbols.set(path, info(path).symbols ?? moduleSymbols(info(path).tree.program)); return memo.symbols.get(path); };
686
- if(!memo.pending.has(root))memo.pending.set(root,readPendingPlatformUsers(root,path=>symbolsOf(path)));
687
- const pendingUsers=memo.pending.get(root), dayOneHosts=g571HostApprovals(root), dayOneMasks=new Map();
688
- // Named approvals waive only their nonblank declaration lines. A physical
689
- // line shared with any unapproved declaration stays charged conservatively.
690
- const dayOneMask = path => {
691
- if (dayOneMasks.has(path)) return dayOneMasks.get(path);
692
- const names=dayOneHosts.get(path), selected=new Set(), unapproved=new Set();
693
- if (names !== undefined && names !== null) {
694
- const sym=symbolsOf(path);
695
- for (const name of names) if (!sym.bindings.has(name)) throw new Error(`Missing G571 binding: ${path}#${name}`);
696
- if (!masks.has(path)) masks.set(path,codeLineMask(text(path),info(path).comments));
697
- const {code,lineOf}=masks.get(path);
698
- for (const [name,row] of sym.bindings) for (const span of row.spans)
699
- for (let line=lineOf(span.start);line<=lineOf(Math.max(span.start,span.end-1));line++)
700
- if (code[line]) (names.has(name)?selected:unapproved).add(line);
701
- for (const line of unapproved) selected.delete(line);
702
- }
703
- dayOneMasks.set(path,selected);return selected;
704
- };
705
- const shaders = path => ignored(path) ? 0 : info(path).shaderLines ?? rawShaderLines(text(path), path, RULES.typescript.test(path) && !path.endsWith('.glsl') ? info(path).tree?.program : undefined);
706
- const count = path => { if (!counts.has(path)) counts.set(path, ignored(path) ? 0 : (path.endsWith('.json') ? shaders(path) : path.endsWith('.glsl') ? shaderCodeLines(text(path)) : linesWithoutComments(text(path), info(path).comments))); return counts.get(path); };
707
- const sdk = exists('src/server/host/package.json') ? JSON.parse(text('src/server/host/package.json')) : null;
708
- const publishedTargetOf = (pkg, spec) => {
709
- const name = `@wildshard/${pkg}`, manifest = pkg === 'sdk' ? sdk : exists(`src/${pkg}/package.json`) ? JSON.parse(text(`src/${pkg}/package.json`)) : null;
710
- if (manifest?.name !== name || !(spec === name || spec?.startsWith(`${name}/`))) return null;
711
- const key = spec === name ? '.' : `.${spec.slice(name.length)}`, target = manifest.exports?.[key];
712
- const path = typeof target === 'string' ? relative(root, resolve(root, `src/${pkg}`, target)).replaceAll('\\', '/') : null;
713
- if (sourceProgress && path !== null && generated.has(path) && !exists(path)) throw new Error(`Source census requires generated source: ${path}`);
714
- return path !== null && exists(path) ? path : null;
715
- };
716
- const publishedTarget = (pkg, spec) => {
717
- const key = `${pkg}\0${String(spec)}`;
718
- if (!targets.has(key)) targets.set(key, publishedTargetOf(pkg, spec));
719
- return targets.get(key);
720
- };
721
- const resolveEdgeOf = (path, spec) => {
722
- const pkg = /^@wildshard\/(sdk|sharddev|game|engine|commons)(?:\/|$)/u.exec(spec ?? '');
723
- const shaderBase = spec?.startsWith('.') ? relative(root, resolve(root, path, '..', spec.split('?')[0])).replaceAll('\\', '/') : null;
724
- const shaderPath = shaderBase?.endsWith('.glsl') && exists(shaderBase) ? shaderBase : null;
725
- const to = spec === null ? null : shaderPath ?? (pkg === null ? null : publishedTarget(pkg[1], spec)) ?? resolveSpecifier(path, spec, exists);
726
- // Local AssemblyScript imports are part of the same authored closure, including extensionless imports.
727
- const base = spec?.startsWith('.') ? relative(root, resolve(root, path, '..', spec)).replaceAll('\\', '/') : null;
728
- const assemblyPath = base === null ? null : [base, `${base}.as`, `${base}/index.as`].find((candidate) => candidate.endsWith('.as') && exists(candidate));
729
- // A local JSON import is data: it resolves to its file, which the folder rules then classify like any other.
730
- const jsonPath = base !== null && base.endsWith('.json') && exists(base) ? base : null;
731
- if (sourceProgress && to === null && assemblyPath === undefined && jsonPath === null) {
732
- const required = base !== null && generated.has(base) ? base : resolveSpecifier(path, spec, candidate => generated.has(candidate));
733
- if (required !== null && !exists(required)) throw new Error(`Source census requires generated source: ${required} (from ${path})`);
734
- }
735
- // Classify the resolved path's namespace components; an audited tree need not contain that namespace.
736
- const local = (to ?? '').split('/');
737
- const trustedLocal = local.length > 3 && local[0] === 'src' && local[1] === 'sharddev' && local[2] === 'runtime';
738
- return { sdk: publishedTarget('sdk', spec) !== null || publishedTarget('sharddev', spec) !== null, trusted: /^@wildshard\/sharddev\/runtime(?:\/|$)/u.test(spec ?? '') || trustedLocal, commons: publishedTarget('commons', spec) !== null, to: to ?? assemblyPath ?? jsonPath ?? null };
739
- };
740
- const resolveEdge = (path, spec) => {
741
- const key = spec === null ? `${path}\0\u0001` : `${path}\0${String(spec)}`;
742
- if (!edges.has(key)) edges.set(key, resolveEdgeOf(path, spec));
743
- return edges.get(key);
744
- };
745
- const graph = (path) => {
746
- if (!graphs.has(path)) graphs.set(path, info(path).specs.map(spec => resolveEdge(path, spec)));
747
- return graphs.get(path);
748
- };
749
- if(!memo.authored.has(root))memo.authored.set(root,Object.fromEntries(readdirSync(resolve(root, 'src/shards'), { withFileTypes: true })
750
- .filter((entry) => entry.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))
751
- .map((entry) => [entry.name, filesIn(resolve(root, 'src/shards', entry.name)).map((path) => relative(root, path))])));
752
- const authoredFiles=memo.authored.get(root);
753
- // Build tools are visible debt, never a runtime root or a second runtime user.
754
- const buildFile = (slug, path) => {
755
- const prefix = `src/shards/${slug}/`;
756
- return path.startsWith(prefix) && /^(?:data|generators)\/|^shard\.config\./u.test(path.slice(prefix.length));
757
- };
758
- const buildUsers = new Map();
759
- for (const [slug, files] of Object.entries(authoredFiles)) {
760
- if (slug === RULES.template) continue;
761
- const queue = files.filter(path => buildFile(slug, path)), seen = new Set();
762
- while (queue.length > 0) {
763
- const path = queue.pop();
764
- if (seen.has(path) || !exists(path) || !sourceFile.test(path)) continue;
765
- seen.add(path);
766
- if (!buildFile(slug, path) && !/^src\/(?:engine|game|sdk|sharddev|commons)\//u.test(path)) continue;
767
- if (/^src\/(?:sdk|sharddev)\//u.test(path)) {
768
- if (!buildUsers.has(path)) buildUsers.set(path, new Set());
769
- buildUsers.get(path).add(slug);
770
- }
771
- for (const edge of graph(path)) if (edge.to !== null) queue.push(edge.to);
772
- }
773
- }
774
- // LD10: a built product ships no runtime TypeScript, so the output basis roots only its verified sections (and
775
- // charges its private section / named JSON bytes); authored runtime files are measured by source progress alone.
776
- const outputs = Object.fromEntries(slugs.map(slug => {
777
- const { sections, customSectionBytes, customSections } = reader.sections(slug);
778
- return [slug, sourceProgress ? {runtime:authoredFiles[slug],sections,customSectionBytes:0,customSections:[]}
779
- : {runtime:[],sections,customSectionBytes,customSections}];
780
- }));
781
- const prefixOf = slug => `${relative(root, resolve(products, representativeProduct(root, slug))).replaceAll('\\', '/')}/`;
782
- const shardFiles = Object.fromEntries(Object.entries(outputs).map(([slug, output]) => [slug, output.runtime.filter(path => !path.endsWith('.d.ts'))]));
783
- const hostFiles = new Map();
784
- for (const [slug, output] of Object.entries(outputs)) {
785
- const path = `${prefixOf(slug)}.section-hosts.ts`;
786
- texts.set(path, sectionHostImports(output.sections, sourceProgress ? '../../' : '../../src/')); probes.set(path, true);
787
- hostFiles.set(slug, path);
788
- }
789
- // Source progress still reports the authored inventory, but build-only imports
790
- // supply no runtime users. A live import into those folders is followed below.
791
- const runtimeRoots = Object.entries(shardFiles).map(([slug, files]) => [slug, sourceProgress ? files.filter(path => !buildFile(slug, path)) : files]);
792
- const consumers = [...runtimeRoots.map(([slug, files]) => [slug, hostFiles.has(slug) ? [...files, hostFiles.get(slug)] : files]), [SHELL_USER, SHELL_ROOTS.filter(exists)]];
793
- const runtimeReached = new Map();
794
- const moduleUsers = new Map();
795
- for (const [slug, files] of consumers) {
796
- // G312: templates are authoring fixtures, never an independent consumer of a platform system.
797
- const prefix = prefixOf(slug), seen = new Set(), queue = files.filter(path => !RULES.tests.test(path));
798
- runtimeReached.set(slug, seen);
799
- while (queue.length > 0) {
800
- const path = queue.pop();
801
- if (seen.has(path)) continue;
802
- seen.add(path);
803
- if (!sourceFile.test(path) || path.endsWith('.d.ts') || RULES.tests.test(path) || !exists(path)) continue;
804
- // Other shards are never consumers of this one's closure; follow defining engine modules too (G303).
805
- if (slug === SHELL_USER ? !path.startsWith('src/') || path.startsWith('src/shards/')
806
- : !path.startsWith(prefix) && !platform(path)) continue;
807
- if (slug !== RULES.template && attributed(path) && (slug !== SHELL_USER || shellControl(path))) {
808
- if (!moduleUsers.has(path)) moduleUsers.set(path, new Set());
809
- moduleUsers.get(path).add(slug);
810
- }
811
- for (const edge of graph(path)) if (edge.to !== null) queue.push(edge.to);
812
- }
813
- }
814
- chargePlatformUsers(moduleUsers, new Map());
815
- const privateModules = new Map(Object.keys(shardFiles).map(slug => [slug, []]));
816
- for (const [path, users] of [...moduleUsers].sort(([a], [b]) => a.localeCompare(b))) {
817
- // This format module enters attribution only for the reviewed arena rows.
818
- if (path.startsWith('src/format/') && platformChargeback(path) === null) continue;
819
- if (RULES.buildOnlySdk.test(path) || users.has(SHELL_USER) || users.size >= RULES.publicUserCount || !(RULES.typescript.test(path) || path.endsWith('.glsl'))) continue;
820
- if (approvedG571Host(dayOneHosts,path)) continue;
821
- const lines = count(path)-dayOneMask(path).size;
822
- const excludedLines=[...dayOneMask(path)].map(line=>line+1);
823
- if (lines > 0) recordPrivateCharge(privateModules, [...users][0], { path, lines, ...(excludedLines.length===0?{}:{excludedLines}) });
824
- }
825
- // G294 per export: a module that two or more shards reach as a file still charges every top-level declaration that
826
- // exactly one shard reaches, through its own imports or transitively through the platform code it reaches.
827
- const bindingUsers = new Map();
828
- const parsedTs = path => RULES.typescript.test(path) && !path.endsWith('.d.ts');
829
- for (const [slug, files] of consumers) {
830
- if (slug === RULES.template) continue;
831
- const rootFiles = new Set(files);
832
- const prefix = prefixOf(slug), seen = new Set(), queue = files.filter(path => !RULES.tests.test(path)).map(path => [path, null]);
833
- const follow = path => typeof path === 'string' && sourceFile.test(path) && !path.endsWith('.d.ts') && !RULES.tests.test(path) && exists(path)
834
- && (slug === SHELL_USER ? path.startsWith('src/') && !path.startsWith('src/shards/')
835
- : path.startsWith(prefix) || platform(path));
836
- // Resolve an exported name (or `*`, every export) to the local declaration(s) behind it; reaching it evaluates the module.
837
- const exported = (path, name, stack = new Set()) => {
838
- if (path === null || !follow(path)) return;
839
- queue.push([path, null]);
840
- if (!parsedTs(path) || stack.has(`${path}\0${name}`)) return;
841
- stack.add(`${path}\0${name}`);
842
- const sym = symbolsOf(path), rows = name === '*' ? [...sym.exports.values()] : sym.exports.has(name) ? [sym.exports.get(name)] : [];
843
- for (const row of rows) {
844
- // `export { imported as name }` forwards to the imported module's export.
845
- const forward = row.local === undefined ? row : sym.imports.get(row.local);
846
- if (forward === undefined) queue.push([path, row.local]); else exported(resolveEdge(path, forward.spec).to, forward.name, stack);
847
- }
848
- if (name === '*' || rows.length === 0) for (const star of sym.stars) exported(resolveEdge(path, star).to, name, stack);
849
- };
850
- const reach = (path, sym, refs) => {
851
- for (const ref of refs) {
852
- const [head, member] = ref.split('\0', 2), parts = ref.split('\0');
853
- if (head === '') {
854
- const target = resolveEdge(path, parts[1]).to;
855
- if (parts[2] === '') { if (target !== null) queue.push([target, null]); }
856
- else exported(target, parts[2] ?? '*');
857
- }
858
- else if (member !== undefined) { const row = sym.imports.get(head); if (row) exported(resolveEdge(path, row.spec).to, member); }
859
- else if (sym.bindings.has(ref)) queue.push([path, ref]);
860
- else if (sym.imports.has(ref)) { const row = sym.imports.get(ref); exported(resolveEdge(path, row.spec).to, row.name); }
861
- }
862
- };
863
- while (queue.length > 0) {
864
- const [path, local] = queue.pop(), key = `${path}\0${local ?? ''}`;
865
- if (seen.has(key) || !follow(path)) continue;
866
- seen.add(key);
867
- if (!parsedTs(path)) { for (const row of graph(path)) if (row.to !== null) queue.push([row.to, null]); continue; }
868
- const sym = symbolsOf(path);
869
- if (local === null) {
870
- // Evaluating a module runs its top-level statements and evaluates its static imports.
871
- for (const spec of sym.statics) { const to = resolveEdge(path, spec).to; if (to !== null) queue.push([to, null]); }
872
- reach(path, sym, sym.init.refs);
873
- // The shard's own folder is the root: every declaration, named import and re-export in it is used (a namespace
874
- // import reaches the members its declarations name, or every export when used bare).
875
- if (slug === SHELL_USER ? rootFiles.has(path) : path.startsWith(prefix)) {
876
- for (const name of sym.bindings.keys()) queue.push([path, name]);
877
- for (const row of sym.imports.values()) if (row.name !== '*') exported(resolveEdge(path, row.spec).to, row.name);
878
- for (const row of sym.exports.values()) if (row.spec !== undefined) exported(resolveEdge(path, row.spec).to, row.name);
879
- for (const star of sym.stars) exported(resolveEdge(path, star).to, '*');
880
- }
881
- continue;
882
- }
883
- const row = sym.bindings.get(local);
884
- if (row === undefined) continue;
885
- if (attributed(path) && (slug !== SHELL_USER || shellControl(path, local))) {
886
- if (!bindingUsers.has(key)) bindingUsers.set(key, new Set());
887
- bindingUsers.get(key).add(slug);
888
- }
889
- reach(path, sym, row.refs);
890
- }
891
- }
892
- chargePlatformUsers(moduleUsers, bindingUsers);
893
- const inlineSpans = new Map(inlinePlatformPaths().filter(path => moduleUsers.has(path)).map(path => [path, inlinePlatformSpans(path, text(path))]));
894
- const privateExports = new Map(Object.keys(shardFiles).map(slug => [slug, []]));
895
- for (const [path, users] of [...moduleUsers].sort(([a], [b]) => a.localeCompare(b))) {
896
- if (RULES.buildOnlySdk.test(path) || (users.size < RULES.publicUserCount && !hasChargebackDeclarations(path)) || !parsedTs(path) || ignored(path)) continue;
897
- if (approvedG571Host(dayOneHosts,path)) continue;
898
- const sym = symbolsOf(path), claimed = new Set([...(inlineSpans.get(path) ?? []).flatMap(span => span.lines),...dayOneMask(path)]);
899
- if (!masks.has(path)) masks.set(path, codeLineMask(text(path), info(path).comments));
900
- const { code, lineOf } = masks.get(path), exportedLocals = new Set([...sym.exports.values()].flatMap(row => row.local ?? []));
901
- const sole = [...sym.bindings].map(([local, row]) => ({ local, row, owners: bindingUsers.get(`${path}\0${local}`) }))
902
- .filter(entry => entry.owners?.size === 1 && !entry.owners.has(SHELL_USER) && !approvedG571Host(dayOneHosts,path,entry.local)
903
- && (!path.startsWith('src/format/') || platformChargeback(path, entry.local) !== null)
904
- && (users.size >= RULES.publicUserCount || platformChargeback(path, entry.local) !== null)).sort((a, b) => a.row.spans[0].start - b.row.spans[0].start);
905
- for (const { local, row, owners } of sole) {
906
- let lines = 0;
907
- for (const span of row.spans) for (let line = lineOf(span.start); line <= lineOf(Math.max(span.start, span.end - 1)); line++) {
908
- if (!claimed.has(line) && code[line]) { claimed.add(line); lines++; }
909
- }
910
- if (lines > 0) recordPrivateCharge(privateExports, [...owners][0], { path, name: local === '\0default' ? 'default' : local, exported: exportedLocals.has(local), lines });
911
- }
912
- }
913
- // Audited branches within shared declarations charge their actual source
914
- // lines once, excluding them from any surrounding sole-binding charge.
915
- for (const [path, spans] of inlineSpans) {
916
- if (!masks.has(path)) masks.set(path, codeLineMask(text(path), info(path).comments));
917
- const { code } = masks.get(path);
918
- for (const span of spans) {
919
- if (approvedG571Host(dayOneHosts,path,span.name)) continue;
920
- const lines = span.lines.filter(line => code[line] && !dayOneMask(path).has(line)).length;
921
- if (lines > 0) recordPrivateCharge(privateExports, undefined, { path, name: span.name, exported: false, lines });
922
- }
923
- }
924
- const trustedRuntime = (slug, path) => {
925
- const prefix = prefixOf(slug), seen = new Set(), queue = [path];
926
- while (queue.length > 0) {
927
- const current = queue.pop();
928
- if (seen.has(current)) continue;
929
- seen.add(current);
930
- if (!current.startsWith(prefix)) continue;
931
- for (const edge of graph(current)) {
932
- if (edge.trusted) return true;
933
- if (edge.to?.startsWith(prefix)) queue.push(edge.to);
934
- }
935
- }
936
- return false;
937
- };
938
- // SF54 dissolved the kit, so no shard-unique kit lines remain to count as custom (the former kit-only column).
939
- const out = {}, listedViews = loadListedViews(root);
940
- for (const [slug, files] of Object.entries(shardFiles)) {
941
- const row = { runtimeLines: 0, trustedRuntimeLines: 0, assemblyScriptLines: 0, conversion: null };
942
- let shardRuntimeLines = 0, rawGlslLines = 0, additionalGlslLines = 0;
943
- const customSources = [], collectSources = includeSources || COMPONENT_SHARDS.includes(slug) || Object.hasOwn(listedViews.shards, slug) && listedViews.shards[slug].length > 0;
944
- for (const path of files) {
945
- const local = path.slice(prefixOf(slug).length), top = local.split('/')[0];
946
- const lines = count(path);
947
- // G315: authored AS is reported separately, without a cap or an effect on the G291 TS ratio.
948
- if (path.endsWith('.as') && !RULES.tests.test(local)) row.assemblyScriptLines += lines;
949
- const sourceOnlyData = sourceProgress && (top==='generators'&&!runtimeReached.get(slug)?.has(path)
950
- || local==='manifest.ts'&&declarationOnlyManifest(text(path),path)
951
- || local==='shard.config.ts'&&declarationOnlyConfig(text(path),path)
952
- || jsonTypeContract(text(path),path)
953
- || generated.has(path)&&sourceData(path)&&declarationOnlyManifest(text(path),path));
954
- if (RULES.typescript.test(path) && !RULES.tests.test(local) && !sourceOnlyData) {
955
- shardRuntimeLines += lines;
956
- if (collectSources && lines > 0) customSources.push({path, kind:'runtime-ts', lines,
957
- ownerPath:`src/shards/${slug}/${local}`});
958
- }
959
- const shaderLines = RULES.tests.test(local) ? 0 : shaders(path);
960
- rawGlslLines += shaderLines;
961
- if (!RULES.typescript.test(path) || sourceOnlyData) {
962
- additionalGlslLines += shaderLines;
963
- if (collectSources && shaderLines > 0) customSources.push({path, kind:'additional-glsl', lines:shaderLines});
964
- }
965
- const trusted = trustedRuntime(slug, path);
966
- if (!path.endsWith('.as') && trusted) row.trustedRuntimeLines += lines;
967
- if (!path.endsWith('.as') && (top === 'runtime' || trusted)) row.runtimeLines += lines;
968
- }
969
- {
970
- // AS remains a separate source visibility column: its shipped executable
971
- // form is Wasm and never adds TS lines to the runtime numerator.
972
- row.assemblyScriptLines = authoredFiles[slug].filter(path => path.endsWith('.as') && !RULES.tests.test(path)).reduce((sum, path) => sum + count(path), 0);
973
- row.customSectionBytes = outputs[slug].customSectionBytes;
974
- row.customSections = outputs[slug].customSections;
975
- row.measurement = 'built-output';
976
- const tools = [...buildUsers].filter(([path, users]) => users.size === 1 && users.has(slug)
977
- && (RULES.buildOnlySdk.test(path) || !moduleUsers.has(path))).map(([path]) => ({path, lines:count(path), bytes:Buffer.byteLength(text(path))}));
978
- row.oneUserBuildTools = {lines:tools.reduce((sum, tool) => sum + tool.lines, 0), files:tools};
979
- }
980
- const baseline = baselines.get(slug);
981
- const legacyLines = baseline?.lines ?? null;
982
- const {modules,exports,pending} = partitionPendingPlatformUsers(slug,privateModules.get(slug),privateExports.get(slug),pendingUsers);
983
- const attributedLines = [...modules, ...exports].reduce((total, module) => total + module.lines, 0);
984
- const customRuntimeLines = shardRuntimeLines + additionalGlslLines + attributedLines;
985
- const asCeiling=legacyLines===null?null:Math.floor(legacyLines/10);
986
- // G454: a visibility column only; AS does not enter the TS numerator or gate.
987
- row.assemblyScriptBudget={ceiling:asCeiling,share:legacyLines===null?null:row.assemblyScriptLines/legacyLines,
988
- passed:asCeiling===null?null:row.assemblyScriptLines<=asCeiling,enforcement:'report-only'};
989
- row.conversion = {
990
- metric: baseline === undefined ? 'native' : 'runtime-vs-legacy', customRuntimeLines, shardRuntimeLines, rawGlslLines, additionalGlslLines,
991
- legacyLines, legacyFolder: baseline === undefined ? null : `${slug}-legacy`, legacyRevision: baseline?.source ?? null,
992
- runtimeShare: legacyLines === null ? null : customRuntimeLines / legacyLines,
993
- passed: legacyLines === null ? null : customRuntimeLines === 0, // G604: every shard's target is zero
994
- gameSystemAttribution: { status: 'import-graph', review: 'G294-primary-reach', lines: attributedLines, modules, exports, pendingSecondUser:pending },
995
- };
996
- if (collectSources) {
997
- for (const module of modules) customSources.push({...module, kind:'sole-module'});
998
- for (const entry of exports) customSources.push({path:entry.path, lines:entry.lines, name:entry.name, kind:'sole-export'});
999
- row.listedView = listedViewInventory(root, slug, customSources, customRuntimeLines, listedViews);
1000
- if (includeSources) row.customSources = customSources;
1001
- if (COMPONENT_SHARDS.includes(slug)) row.components = componentInventory(root, slug, customSources, customRuntimeLines);
1002
- }
1003
- row.listedView ??= listedViewInventory(root, slug, [], customRuntimeLines, listedViews);
1004
- out[slug] = row;
1005
- }
1006
- return out;
1007
- }
1008
- /** Authoritative P4 measure over verified output sections. A missing or corrupt product refuses;
1009
- * authoring files never substitute for missing output or supply G294 users. */
1010
- /** @param {string} root @param {boolean} includeSources @param {string} products @param {string[]|null} only */
1011
- export function outputShardLines(root = ROOT, includeSources = false, products = resolve(root, 'out'), only = null) {
1012
- const closures = runtimeClosures(root);
1013
- const closed = Object.keys(closures).filter(slug => closures[slug].status === 'closed');
1014
- if (only?.some(slug => !closed.includes(slug))) throw new Error('Output measurement requested an unclosed shard');
1015
- return countOutput(root, includeSources, products, only ?? closed);
1016
- }
1017
- /** The canonical measure is output-only. Unclosed shards have no row/percentage;
1018
- * runtimeClosures supplies their explicit work queue to reports. */
1019
- export function shardLines(root = ROOT, includeSources = false) {
1020
- return outputShardLines(root, includeSources);
1021
- }
1022
- /** Source-basis progress inventory, including component spans and sole-user charges.
1023
- * Requires every generated product's verified section inventory; never samples a partial out/.
1024
- * Never supplies canonical output percentages for an unclosed shard. */
1025
- export function sourceProgressInventory(root = ROOT, products = resolve(root,'out')) {
1026
- const rows=countOutput(root,true,resolve(root,'src/shards'),Object.keys(runtimeClosures(root)),true,products);
1027
- return Object.fromEntries(Object.entries(rows).map(([slug,row])=>[slug,{...row,measurement:'source'}]));
1028
- }
1029
- /** G458 progress only. The canonical custom percentage remains unavailable for
1030
- * unclosed shards. Preserve the predecessor's source/G294 law for this labelled
1031
- * estimate rather than disguising the output/source unit change as a cut. */
1032
- export function sourceProgressLines(root = ROOT, products = resolve(root,'out')) {
1033
- const rows=countOutput(root,false,resolve(root,'src/shards'),Object.keys(runtimeClosures(root)),true,products);
1034
- return progressLines(rows);
1035
- }
1036
- function progressLines(rows) {
1037
- return Object.fromEntries(Object.entries(rows).map(([slug,row])=>[slug,{basis:'source',
1038
- customLines:row.conversion.customRuntimeLines,legacyLines:row.conversion.legacyLines,
1039
- assemblyScriptLines:row.assemblyScriptLines,assemblyScriptBudget:row.assemblyScriptBudget}]));
1040
- }
1041
- /** One immutable report shares syntax facts across output and source attribution.
1042
- * Resolution, ownership and components still run separately for both bases.
1043
- * @param {string} root @param {string} products */
1044
- export function outputCensus(root = ROOT, products = resolve(root,'out'), reader = createOutputReader(root,products)) {
1045
- const closure=runtimeClosures(root),closed=Object.keys(closure).filter(slug=>closure[slug].status==='closed');
1046
- const memo=censusMemo();
1047
- const measures=countOutput(root,true,products,closed,false,products,memo,reader);
1048
- const rows=countOutput(root,true,resolve(root,'src/shards'),Object.keys(closure),true,products,memo,reader);
1049
- const inventory=Object.fromEntries(Object.entries(rows).map(([slug,row])=>[slug,{...row,measurement:'source'}]));
1050
- return {measures,inventory,source:progressLines(rows)};
1051
- }
1052
- /** Headless availability is reported separately from the custom/frozen measure. */
1053
- export function milestoneFlags(_slug, _row, root = ROOT) {
1054
- return { headless: existsSync(resolve(root, 'test/shard-headless.test.ts')) };
1055
- }
1056
- export function checkShares(recorded, lines) {
1057
- const failures = [];
1058
- for (const slug of Object.keys(lines)) if (!Object.hasOwn(recorded.baseline, slug)) failures.push(`${slug}: unknown shard (no baseline in ${LIST})`);
1059
- for (const [slug, row] of Object.entries(lines)) {
1060
- if (Object.hasOwn(recorded.enforced, slug) && row.conversion.passed === false) failures.push(`${slug}: custom runtime is not zero (G604)`);
1061
- }
1062
- return failures;
1063
- }
1064
- if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
1065
- // Do not top-level-await this import: the CLI reads this module's exports.
1066
- // The detached async launcher lets evaluation settle before the CLI runs.
1067
- const launch=async()=>{
1068
- try {await Promise.reject(new Error('The shard-platform CLI is sharddev\'s'));}
1069
- catch(error){console.error(error);process.exitCode=1;}
1070
- };
1071
- void launch();
1072
- }