Repository navigation
Expand file tree
/
Copy pathCompilerBase.ts
More file actions
1326 lines (1235 loc) · 47.2 KB
/
Copy pathCompilerBase.ts
File metadata and controls
1326 lines (1235 loc) · 47.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createHash } from 'crypto';
/**
* Base Compiler Interface with Agent Identity Integration
*
* Provides common RBAC validation logic for all HoloScript compilers.
* Supports dual-mode access control: legacy JWT RBAC tokens AND UCAN
* capability tokens via the P3 Migration Bridge.
*
* All compilers MUST extend this base or implement ICompiler interface.
*
* @version 2.0.0
*/
import { getRBAC, ResourceType, type AccessDecision } from './identity/AgentRBAC';
import { WorkflowStep } from './identity/AgentIdentity';
import type { CulturalProfileMetadata } from './identity';
import type { CulturalCompatibilityResult } from './CulturalCompatibilityChecker';
import type {
HoloComposition,
HoloDomainBlock,
HoloObjectDecl,
HoloSpatialGroup,
} from '../parser/HoloCompositionTypes';
import type {
GLTFExportResult,
ARCompilationResult,
AndroidXRCompileResult,
VRRCompilationResult,
IOSCompileResult,
} from './CompilerTypes';
import { CapabilityRBAC, getCapabilityRBAC } from './identity/CapabilityRBAC';
import type { CapabilityToken } from './identity/CapabilityToken';
import { type CompilerName, COMPILER_ANS_MAP, isValidCompilerName } from './identity/ANSNamespace';
import {
type SpatialZoneEnforcer,
type SpatialAccessDecision,
SpatialPermission,
getSpatialZoneEnforcer,
} from './identity/SpatialMemoryZones';
import {
CompilerDocumentationGenerator,
type TripleOutputResult,
type DocumentationGeneratorOptions,
type TripleOutputGenerationMeta,
} from './CompilerDocumentationGenerator';
import type { JsonLdSceneGraph } from './SemanticSceneGraph';
// ---------------------------------------------------------------------------
// Dual-mode token types (P3 Migration Bridge)
// ---------------------------------------------------------------------------
/**
* Credential wrapper for UCAN capability tokens.
*
* Bundles the token with the issuer's Ed25519 public key, which is
* required for signature verification.
*/
export interface CapabilityTokenCredential {
/** UCAN capability token object */
capabilityToken: CapabilityToken;
/** Ed25519 public key of the token issuer (PEM-encoded) */
issuerPublicKey: string;
}
/**
* Union type for compiler access tokens.
*
* - `string`: Legacy JWT RBAC token (routed to AgentRBAC)
* - `CapabilityTokenCredential`: UCAN capability token (routed to CapabilityRBAC)
*
* This enables the P3 Migration Bridge: callers can present either token type
* and CompilerBase will route to the appropriate verification system.
*/
export type CompilerToken = string | CapabilityTokenCredential;
/**
* Type guard to check if a token is a UCAN CapabilityTokenCredential.
*
* UCAN credential objects have `capabilityToken` and `issuerPublicKey` fields.
* JWT tokens are plain strings.
*/
export function isCapabilityTokenCredential(
token: CompilerToken | undefined | null
): token is CapabilityTokenCredential {
if (!token || typeof token === 'string') return false;
return (
typeof token === 'object' &&
'capabilityToken' in token &&
'issuerPublicKey' in token &&
token.capabilityToken != null &&
typeof token.issuerPublicKey === 'string'
);
}
// ---------------------------------------------------------------------------
// Compiler class name to ANS CompilerName mapping
// ---------------------------------------------------------------------------
/**
* Maps compiler class names (e.g. 'UnityCompiler') to their ANS compiler
* name (e.g. 'unity'). Used by the default `getRequiredCapability()` to
* derive the ANS namespace from the class's `compilerName` property.
*/
const COMPILER_CLASS_TO_ANS_NAME: Readonly<Record<string, CompilerName>> = {
UnityCompiler: 'unity',
UnrealCompiler: 'unreal',
GodotCompiler: 'godot',
Canvas2DGameCompiler: 'canvas2d-game',
VRChatCompiler: 'vrchat',
OpenXRCompiler: 'openxr',
OpenXRSpatialEntitiesCompiler: 'openxr-spatial-entities',
VisionOSCompiler: 'visionos',
AndroidXRCompiler: 'android-xr',
QuestCompiler: 'quest',
AIGlassesCompiler: 'ai-glasses',
AndroidCompiler: 'android',
IOSCompiler: 'ios',
// ARCompiler, BabylonCompiler, PlayCanvasCompiler, ThreeJSCompiler, R3FCompiler — retired (apex-poison, 2026-06-17)
WebGPUCompiler: 'webgpu',
WASMCompiler: 'wasm',
TSLCompiler: 'tsl',
URDFCompiler: 'urdf',
SDFCompiler: 'sdf',
USDPhysicsCompiler: 'usd',
GLTFPipeline: 'gltf',
GaussianSplattingCompiler: '3dgs',
DTDLCompiler: 'dtdl',
NFTMarketplaceCompiler: 'nft-marketplace',
SCMCompiler: 'scm',
// VRRCompiler — retired (apex-poison, 2026-06-17)
A2AAgentCardCompiler: 'a2a-agent-card',
MultiLayerCompiler: 'multi-layer',
IncrementalCompiler: 'incremental',
StateCompiler: 'state',
TraitCompositionCompiler: 'trait-composition',
DomainBlockCompilerMixin: 'domain-block',
NIRCompiler: 'nir',
URDFToUSDZConverter: 'urdf',
QuiltCompiler: 'quilt',
MVHEVCCompiler: 'mv-hevc',
NodeServiceCompiler: 'node-service',
SDKCompiler: 'sdk',
NextJSAPICompiler: 'nextjs-api',
MCPConfigCompiler: 'mcp-config',
HoloMCPCompiler: 'mcp-server',
AgentInferenceCompiler: 'agent-inference',
OmnigentAgentYamlCompiler: 'omnigent-agent-yaml',
DaimonSeedCompiler: 'daimon-seed',
HSIIRCompiler: 'hsi-ir',
CodeEditorCompiler: 'code-editor',
SVGCompiler: 'svg',
};
export function getRegisteredCompilerANSName(compilerClassName: string): CompilerName | undefined {
return COMPILER_CLASS_TO_ANS_NAME[compilerClassName];
}
/**
* Base compiler options (extended by specific compilers)
*/
export interface BaseCompilerOptions {
/**
* Generate triple-output documentation (llms.txt, .well-known/mcp, markdown)
* @default false
*/
generateDocs?: boolean;
/**
* Documentation generator options (only used if generateDocs is true)
*/
docsOptions?: DocumentationGeneratorOptions;
/**
* Attach a provenance hash to compilation output for audit-trail traceability.
* When set, compilers SHOULD embed this value as a comment in their output.
* Format: `// Provenance Hash: <hex>` (use `#` prefix for YAML/GDScript targets).
*/
provenanceHash?: string;
}
/**
* Compilation result with optional documentation outputs
*/
export interface CompilationResult {
/** Primary compilation output (code, GLTF, etc.) */
output:
| string
| Record<string, string>
| GLTFExportResult
| ARCompilationResult
| VRRCompilationResult
| AndroidXRCompileResult
| IOSCompileResult
/** Structured outputs (e.g. WASM bundle) when paired with triple-output docs */
| Record<string, unknown>;
/** Optional documentation bundle (if generateDocs enabled) */
documentation?: TripleOutputResult;
}
/** What {@link flattenCompositionScenes} hands a compiler that builds one world. */
export interface FlattenedScenes {
/** The composition to compile: the input itself when no scene adds anything. */
composition: HoloComposition;
/**
* Scene environments that are not applied. `appliedFrom` names the scene whose
* environment applies instead, or is `null` when the composition's own does.
*/
unappliedEnvironments: Array<{ scene: string; appliedFrom: string | null }>;
/**
* Scene objects that are not built, because `takenName` (the object's own name,
* the name of an object inside it, or an identifier building it would declare)
* gives an identifier something already in the output declares. `takenBy` is
* the compiler's plain words for that something ("a light", "the camera");
* without it, it is another object. Only filled when the compiler passes
* `identifierOf` or `declared`.
*/
leftOutObjects: Array<{ scene: string; object: string; takenName: string; takenBy?: string }>;
}
/**
* The identifiers a compiler declares in the one scope it builds objects in,
* beyond the one each object's name gives. See {@link flattenCompositionScenes}.
*/
export interface DeclaredIdentifiers {
/**
* Every identifier the compiler declares in that scope when it compiles
* `content`, each mapped to plain words for the part that declares it ("a
* light", "the camera"). `content` is the composition as it will be compiled,
* without the objects scenes add. Called at most once, and only when a scene
* has objects to add.
*/
reserved?(content: HoloComposition): ReadonlyMap<string, string>;
/**
* Every identifier building `obj` declares in that scope, with those of the
* objects inside it: its name's own, and any the compiler derives from it.
*/
of?(obj: HoloObjectDecl): string[];
}
/**
* Compiler interface with agent identity enforcement
*/
export interface ICompiler {
/**
* Compile HoloComposition AST to target platform code
*
* @param composition - HoloScript AST
* @param agentToken - JWT token proving agent identity
* @param outputPath - Optional output file path for scope validation
* @param sceneGraph - Optional pre-computed SSG for capability inference and optimization hints
* @returns Compiled code (string or multi-file object)
* @throws UnauthorizedCompilerAccessError if token invalid or lacks permissions
*/
compile(
composition: HoloComposition,
agentToken: string,
outputPath?: string,
sceneGraph?: JsonLdSceneGraph
):
| string
| Record<string, string>
| GLTFExportResult
| ARCompilationResult
| VRRCompilationResult
| AndroidXRCompileResult
| IOSCompileResult
| any;
}
/**
* Error thrown when agent lacks required permissions
*/
export class UnauthorizedCompilerAccessError extends Error {
constructor(
public readonly decision: AccessDecision,
public readonly operation: string,
public readonly compilerName: string
) {
super(
`[${compilerName}] Unauthorized ${operation}: ${decision.reason || 'Access denied'}\n` +
`Required Permission: ${decision.requiredPermission || 'unknown'}`
);
this.name = 'UnauthorizedCompilerAccessError';
}
}
/**
* Base compiler class with RBAC enforcement
*
* All compilers SHOULD extend this class to inherit:
* - AST access validation
* - Code generation validation
* - Output path scope validation
* - Clear error messages
*
* Example:
* ```typescript
* export class UnityCompiler extends CompilerBase {
* compile(composition: HoloComposition, agentToken: string, outputPath?: string): string {
* // Validate AST access
* this.validateASTAccess(agentToken);
*
* // Validate code generation permission
* this.validateCodeGeneration(agentToken);
*
* // Validate output path (if provided)
* if (outputPath) {
* this.validateOutputPath(agentToken, outputPath);
* }
*
* // Perform compilation...
* return csharpCode;
* }
* }
* ```
*/
/**
* Supported compilation targets for string sanitization.
*
* SECURITY: Every target that generates code must have an entry here.
* Using the wrong target (e.g. 'TypeScript' for Kotlin output) is a
* Cross-Agent Compilation Injection vulnerability (CWE-94).
*/
export type EscapeTarget =
| 'Solidity'
| 'Swift'
| 'Kotlin'
| 'CSharp'
| 'GDScript'
| 'JSX'
| 'TypeScript'
| 'GLSL'
| 'HLSL'
| 'WGSL'
| 'Python'
| 'Lua'
| 'USD'
| 'XML'
| 'JSON'
| 'Rust';
function escapeCStyle(value: string): string {
return value
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\0/g, '\\0');
}
function escapeGDScript(value: string): string {
return value
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
.replace(/\0/g, '');
}
function escapeJSX(value: string): string {
return value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\{/g, '{')
.replace(/\}/g, '}');
}
function escapeXML(value: string): string {
return value
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function escapeShader(value: string): string {
return value
.replace(/\\/g, '')
.replace(/\*/g, '')
.replace(/\//g, '')
.replace(/#/g, '')
.replace(/\n/g, ' ')
.replace(/\r/g, '');
}
function escapePython(value: string): string {
return value
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/\0/g, '\\x00');
}
function escapeLua(value: string): string {
return value
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\0/g, '\\0');
}
function escapeUSD(value: string): string {
return value
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r');
}
function escapeJSON(value: string): string {
return value
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t')
.replace(/[\x00-\x1f]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
}
export function escapeStringValue(value: string, target: EscapeTarget): string {
if (!value) return value;
switch (target) {
case 'Solidity':
case 'CSharp':
case 'Swift':
case 'Kotlin':
case 'TypeScript':
case 'Rust':
return escapeCStyle(value);
case 'GDScript':
return escapeGDScript(value);
case 'JSX':
return escapeJSX(value);
case 'XML':
return escapeXML(value);
case 'GLSL':
case 'HLSL':
case 'WGSL':
return escapeShader(value);
case 'Python':
return escapePython(value);
case 'Lua':
return escapeLua(value);
case 'USD':
return escapeUSD(value);
case 'JSON':
return escapeJSON(value);
default:
return value;
}
}
/**
* Read `scene` blocks the way a compiler that builds ONE world reads the rest of
* the composition.
*
* The parser keeps what a `scene "X" { ... }` block holds on `composition.scenes`,
* not on `composition.objects`. A compiler that reads only `composition.objects`
* therefore leaves every object written inside a scene out of its output, and
* says nothing. Such a compiler calls this before it compiles and then compiles
* the composition it returns: each scene's objects follow the top-level objects,
* scene by scene, and go through the compiler's own object path. A scene has no
* transform, so each object keeps its own position. Compilers that extend
* {@link CompilerBase} call it through {@link CompilerBase.flattenScenes};
* SceneIRCompiler and the Quest world emitter, which do not extend it, call it directly.
*
* Environment: the composition's own `environment` applies when it has one;
* otherwise the first scene that declares one supplies it. One world has one
* environment, so every other scene environment is listed in
* `unappliedEnvironments`, with the one that applies instead.
*
* Names: scenes are separate in the source but become one world here. A compiler
* that turns object names into identifiers passes `identifierOf`. A scene object
* is then not built when it, or an object inside it, would get an identifier that
* an object already in the output has (two scenes that each have a "Ground", or
* a scene reusing a top-level name); it is listed in `leftOutObjects` instead of
* producing output that cannot load. Objects are not the only things a compiler
* names: one that also declares identifiers for other parts (lights, sounds, the
* camera), or derives more than one from an object, passes `declared`, and a
* scene object is then also left out when building it would declare one already
* declared. Only the compiler knows what it names, so it says; this does not
* guess. Clashes among the composition's own content are left alone, so its
* output stays exactly as before.
*
* A compiler that has somewhere to report writes {@link CompilerBase.sceneWarnings}
* (an emitter that is not a compiler class, {@link describeLeftOutScenes}) into its
* output, so nothing is left out without being named. When no scene adds
* anything, the input itself is returned, so a composition without scenes compiles
* exactly as before. The input is never changed.
*/
export function flattenCompositionScenes(
composition: HoloComposition,
identifierOf?: (name: string) => string,
declared?: DeclaredIdentifiers
): FlattenedScenes {
const scenes = composition.scenes ?? [];
const unappliedEnvironments: FlattenedScenes['unappliedEnvironments'] = [];
const leftOutObjects: FlattenedScenes['leftOutObjects'] = [];
let environment = composition.environment;
let appliedFrom: string | null = null;
for (const scene of scenes) {
if (!scene.environment) continue;
if (environment) {
unappliedEnvironments.push({ scene: scene.name, appliedFrom });
} else {
environment = scene.environment;
appliedFrom = scene.name;
}
}
// Every name in these objects and in the objects inside them.
const namesIn = (objects: HoloObjectDecl[] | undefined, into: string[]): string[] => {
for (const obj of objects ?? []) {
into.push(String(obj.name ?? ''));
namesIn(obj.children, into);
}
return into;
};
const groupNames = (groups: HoloSpatialGroup[] | undefined, into: string[]): string[] => {
for (const group of groups ?? []) {
namesIn(group.objects, into);
groupNames(group.groups, into);
}
return into;
};
// Each identifier already declared, with the compiler's words for what declares
// it (undefined: another object). Filled only when a scene has objects to add.
const taken = new Map<string, string | undefined>();
const take = (identifier: string, by?: string) => {
if (!taken.has(identifier)) taken.set(identifier, by);
};
const checked = identifierOf !== undefined || declared !== undefined;
if (checked && scenes.some((scene) => (scene.objects ?? []).length > 0)) {
if (identifierOf) {
for (const name of namesIn(composition.objects, groupNames(composition.spatialGroups, []))) {
take(identifierOf(name));
}
}
const content =
environment === composition.environment ? composition : { ...composition, environment };
for (const [identifier, by] of declared?.reserved?.(content) ?? []) take(identifier, by);
}
const sceneObjects: HoloObjectDecl[] = [];
for (const scene of scenes) {
for (const obj of scene.objects ?? []) {
if (checked) {
// [the name a warning quotes, the identifier it gives]: each name as the
// source spells it first, then what the compiler says building it declares.
const claims: Array<[string, string]> = [
...(identifierOf
? namesIn([obj], []).map((name): [string, string] => [name, identifierOf(name)])
: []),
...(declared?.of?.(obj) ?? []).map((id): [string, string] => [id, id]),
];
const clash = claims.find(([, identifier]) => taken.has(identifier));
if (clash) {
const takenBy = taken.get(clash[1]);
leftOutObjects.push({
scene: scene.name,
object: String(obj.name ?? ''),
takenName: clash[0],
...(takenBy === undefined ? {} : { takenBy }),
});
continue;
}
for (const [, identifier] of claims) take(identifier);
}
sceneObjects.push(obj);
}
}
if (sceneObjects.length === 0 && environment === composition.environment) {
return { composition, unappliedEnvironments, leftOutObjects };
}
return {
composition: {
...composition,
objects: [...(composition.objects ?? []), ...sceneObjects],
...(environment ? { environment } : {}),
},
unappliedEnvironments,
leftOutObjects,
};
}
/**
* One plain sentence for each piece of scene content {@link flattenCompositionScenes} left out,
* with names escaped for `target` and kept on one line. A compiler that extends
* {@link CompilerBase} gets these from {@link CompilerBase.sceneWarnings}; an emitter that is a
* function of its own calls this, and writes each sentence into its output as a WARNING comment.
*/
export function describeLeftOutScenes(flattened: FlattenedScenes, target: EscapeTarget): string[] {
const oneLine = (text: string) => text.replace(/[\r\n\u2028\u2029]+/g, ' ');
const quote = (name: string) => `"${escapeStringValue(oneLine(name), target)}"`;
return [
...flattened.unappliedEnvironments.map(({ scene, appliedFrom }) => {
const applied =
appliedFrom === null
? "the composition's own environment"
: `the environment in scene ${quote(appliedFrom)}`;
return `the environment in scene ${quote(scene)} is not applied: this output is one world with one environment, and ${applied} applies.`;
}),
...flattened.leftOutObjects.map(
({ scene, object, takenName, takenBy = 'another object' }) =>
`object ${quote(object)} in scene ${quote(scene)} is not built: this output is one world, and ${oneLine(takenBy)} in it already uses the name ${quote(takenName)}.`
),
];
}
/**
* Read `group "X" { ... }` blocks as the spatial groups they describe.
*
* The `.holo` spelling of a group is `spatial_group`, and `group` is not a
* keyword. The parser still accepts `group "X" { ... }`, the way it accepts any
* block it does not know: it keeps it on `composition.domainBlocks` as a custom
* domain block, with the objects written inside it on `children` and its other
* lines (`position: [...]`, ...) on `properties`. A compiler that builds objects
* from `composition.objects` and `composition.spatialGroups` therefore leaves
* every object inside such a block out of its output, and says nothing, while
* the `.hsplus` reading of the same text draws them inside their group.
*
* This returns a composition in which each such block is a spatial group
* instead: the same name, its lines as the group's properties (so `position`,
* `rotation` and `scale` move the group the way they move a `spatial_group`), and
* its objects inside it, each keeping its own position relative to the group.
* The groups follow the composition's own spatial groups, in source order, and
* the blocks leave `domainBlocks`, so nothing reads them twice. A compiler calls
* this before it compiles and then compiles the composition it returns. If it
* also calls {@link flattenCompositionScenes}, it calls this first: flattening
* then counts the objects inside these groups among the names already in use, so
* with `identifierOf` a scene object that would clash with one of them is left
* out and listed, rather than built twice under one identifier.
*
* Not carried over, because a spatial group has no place for them: the block's
* `@trait` names (each trait's settings stay among the properties) and its
* `on...` handlers. A `group` written inside a group block is read by the parser
* as one of that block's properties, not as a block, so it is not read either.
*
* Without group blocks the input itself is returned, so such a composition
* compiles exactly as before. The input is never changed.
*/
export function readGroupBlocksAsSpatialGroups(composition: HoloComposition): HoloComposition {
const blocks = composition.domainBlocks ?? [];
const isGroupBlock = (block: HoloDomainBlock) =>
block.domain === 'custom' && String(block.keyword ?? '').toLowerCase() === 'group';
if (!blocks.some(isGroupBlock)) return composition;
const groups: HoloSpatialGroup[] = [];
const otherBlocks: HoloDomainBlock[] = [];
for (const block of blocks) {
if (!isGroupBlock(block)) {
otherBlocks.push(block);
continue;
}
groups.push({
type: 'SpatialGroup',
name: block.name,
properties: Object.entries(block.properties ?? {}).map(([key, value]) => ({
type: 'GroupProperty' as const,
key,
value,
})),
objects: block.children ?? [],
...(block.loc ? { loc: block.loc } : {}),
});
}
return {
...composition,
domainBlocks: otherBlocks,
spatialGroups: [...(composition.spatialGroups ?? []), ...groups],
};
}
export abstract class CompilerBase implements ICompiler {
protected rbac = getRBAC();
/**
* Sanitizes a string value for injection into a specific compiler target language.
* Mitigates Cross-Agent Compilation Injection attacks (e.g. CWE-94).
*
* @param value The raw string value from the AST
* @param target The compilation target language
* @returns The escaped/sanitized string safe for interpolation
*/
public escapeStringValue(value: string, target: EscapeTarget): string {
return escapeStringValue(value, target);
}
/**
* Lazy-initialized CapabilityRBAC adapter for UCAN token verification.
* Only created when a UCAN capability token is first encountered.
*/
private _capabilityRBAC: CapabilityRBAC | null = null;
/**
* Lazy-initialized SpatialZoneEnforcer for compile-time spatial zone checks.
* Only created when spatial zone validation is first invoked.
*/
private _spatialZoneEnforcer: SpatialZoneEnforcer | null = null;
/**
* Lazy-initialized documentation generator for triple-output compilation.
* Only created when generateDocs option is enabled.
*/
private _documentationGenerator: CompilerDocumentationGenerator | null = null;
/**
* Compiler name (for error messages)
*/
protected abstract readonly compilerName: string;
/**
* Compile HoloComposition AST to target platform code
* MUST be implemented by subclasses
*/
abstract compile(
composition: HoloComposition,
agentToken: string,
outputPath?: string,
sceneGraph?: JsonLdSceneGraph
):
| string
| Record<string, string>
| GLTFExportResult
| ARCompilationResult
| VRRCompilationResult
| AndroidXRCompileResult
| IOSCompileResult
| any;
/**
* Compile to a path-keyed file map: relative output path → file contents.
*
* This is the standardized "emits buildable source" contract every target
* shares — the byte-diff golden gates and the build-verify runner both consume
* a `Record<string, string>`, so any target that implements this can be
* gate-enforced and build-verified without bespoke per-target plumbing.
*
* The default handles two shapes: a single `string` (wrapped under
* `defaultOutputFileName()`) and a string-valued object map (passed through).
* A `compile()` result with no string output (binary/typed objects, e.g.
* GLTFExportResult) THROWS rather than emit `"[object Object]"` garbage — those
* targets must override. Multi-file targets (Android, AndroidXR) already override
* to emit a full project layout. Auth is delegated to `compile()`, which each
* subclass already gates; this method does not re-validate.
*
* @param composition - HoloScript AST
* @param agentToken - JWT token proving agent identity (default '' bypasses RBAC)
* @returns Map of relative output path → file contents
*/
compileToFiles(composition: HoloComposition, agentToken = ''): Record<string, string> {
const result = this.compile(composition, agentToken);
if (typeof result === 'string') {
return { [this.defaultOutputFileName()]: result };
}
if (result && typeof result === 'object') {
// Already path-keyed (or close enough) — keep string entries as-is.
const out: Record<string, string> = {};
for (const [k, v] of Object.entries(result as Record<string, unknown>)) {
if (typeof v === 'string') out[k] = v;
}
if (Object.keys(out).length > 0) return out;
}
// Fail loud: a compile() result with no string output (e.g. GLTFExportResult — binary/object
// fields only) cannot be represented as a source-file map by the default. Emitting
// String(result) would feed "[object Object]" to the byte-diff gate and build-verify runner —
// silent garbage. Such targets MUST override compileToFiles().
throw new Error(
`${this.constructor.name}.compileToFiles(): compile() produced no string output ` +
`(binary/object result); this target must override compileToFiles() to emit a path-keyed source map.`
);
}
/**
* Default single-file output name for the wrapping `compileToFiles()` default.
* Override to name a single-file target's emit (e.g. `index.ts`, `Main.kt`).
*/
protected defaultOutputFileName(): string {
return 'output.txt';
}
/**
* {@link flattenCompositionScenes}, for a compiler that extends this base. It
* calls this at the start of `compile()`, compiles the composition it returns,
* and writes {@link CompilerBase.sceneWarnings} into its output.
*/
protected flattenScenes(
composition: HoloComposition,
identifierOf?: (name: string) => string,
declared?: DeclaredIdentifiers
): FlattenedScenes {
return flattenCompositionScenes(composition, identifierOf, declared);
}
/**
* One plain sentence for each piece of scene content {@link CompilerBase.flattenScenes}
* left out, with names escaped for `target` and kept on one line. The compiler
* writes each sentence into its output as a WARNING comment.
*/
protected sceneWarnings(flattened: FlattenedScenes, target: EscapeTarget): string[] {
return describeLeftOutScenes(flattened, target);
}
// =========================================================================
// P3 Migration Bridge: Dual-mode token support
// =========================================================================
/**
* Get or create the CapabilityRBAC adapter instance.
*
* Lazily initialized to avoid overhead when only JWT tokens are used.
*/
protected getCapabilityRBAC(): CapabilityRBAC {
if (!this._capabilityRBAC) {
this._capabilityRBAC = getCapabilityRBAC();
}
return this._capabilityRBAC;
}
/**
* Get or create the SpatialZoneEnforcer instance.
*
* Lazily initialized to avoid overhead when spatial zones are not in use.
*/
protected getSpatialZoneEnforcer(): SpatialZoneEnforcer {
if (!this._spatialZoneEnforcer) {
this._spatialZoneEnforcer = getSpatialZoneEnforcer();
}
return this._spatialZoneEnforcer;
}
/**
* Get or create the CompilerDocumentationGenerator instance.
*
* Lazily initialized to avoid overhead when documentation generation is disabled.
*
* @param options - Documentation generator options
*/
protected getDocumentationGenerator(
options?: DocumentationGeneratorOptions
): CompilerDocumentationGenerator {
if (!this._documentationGenerator) {
this._documentationGenerator = new CompilerDocumentationGenerator(options);
}
return this._documentationGenerator;
}
/**
* Generate triple-output documentation for a compilation result.
*
* This is a utility method that subclasses can call after successful compilation
* to generate llms.txt, .well-known/mcp, and markdown documentation.
*
* @param composition - Parsed HoloScript composition AST
* @param compiledCode - The compiled output code
* @param options - Documentation generator options
* @returns Triple-output documentation bundle
*
* @example
* ```typescript
* compile(composition: HoloComposition, agentToken: string, options?: MyCompilerOptions): CompilationResult {
* this.validateCompilerAccess(agentToken);
* const code = this.performCompilation(composition);
*
* if (options?.generateDocs) {
* const docs = this.generateDocumentation(composition, code, options.docsOptions);
* return { output: code, documentation: docs };
* }
*
* return { output: code };
* }
* ```
*/
protected generateDocumentation(
composition: HoloComposition,
compiledCode: string | Record<string, string>,
options?: DocumentationGeneratorOptions,
generationMeta?: TripleOutputGenerationMeta
): TripleOutputResult {
const generator = this.getDocumentationGenerator(options);
return generator.generate(composition, this.compilerName, compiledCode, generationMeta);
}
/**
* Normalize primary compiler output for llms.txt / markdown (avoid huge/binary payloads).
*/
protected serializeOutputForDocumentation(
output: CompilationResult['output']
): string | Record<string, string> {
if (typeof output === 'string') {
return output.length > 200_000 ? output.slice(0, 200_000) : output;
}
if (output && typeof output === 'object') {
const rec = output as Record<string, unknown>;
if ('gltf' in rec || 'buffers' in rec) {
return {
_kind: 'binary_or_gltf_bundle',
keys: Object.keys(rec).join(','),
};
}
const vals = Object.values(rec);
if (vals.length > 0 && vals.every((v) => typeof v === 'string')) {
return rec as Record<string, string>;
}
try {
const json = JSON.stringify(output);
return json.length > 200_000 ? json.slice(0, 200_000) : json;
} catch {
return { _kind: 'non_serializable', keys: Object.keys(rec).join(',') };
}
}
return String(output);
}
/** Short digest for MCP card `_meta.holoscript.compilation_digest`. */
protected digestForDocumentation(docPayload: string | Record<string, string>): string {
const payload = typeof docPayload === 'string' ? docPayload : JSON.stringify(docPayload);
return createHash('sha256').update(payload).digest('hex').slice(0, 16);
}
/**
* When `generateDocs` is set on {@link BaseCompilerOptions}, returns a {@link CompilationResult}
* with `documentation` (llms.txt, .well-known/mcp, markdown); otherwise returns `output` unchanged.
*/
protected withTripleOutputIfRequested(
composition: HoloComposition,
output: unknown,
opts?: BaseCompilerOptions
): unknown | CompilationResult {
if (!opts?.generateDocs) {
return output;
}
const docPayload = this.serializeOutputForDocumentation(output as CompilationResult['output']);
const generationMeta: TripleOutputGenerationMeta = {
compilationDigest: this.digestForDocumentation(docPayload),
};
const documentation = this.generateDocumentation(
composition,
docPayload,
opts.docsOptions,
generationMeta
);
return { output, documentation };
}
/**
* Get the ANS capability namespace path for this compiler.
*
* Subclasses MAY override this to specify their exact ANS namespace.
* The default implementation derives it from `compilerName` using the
* `COMPILER_CLASS_TO_ANS_NAME` lookup table.
*
* @returns The ANS capability path (e.g., "/compile/web3d/r3f"), or
* `undefined` if the compiler has no registered ANS namespace.
*
* @example
* ```typescript
* // Default: derives from compilerName
* class R3FCompiler extends CompilerBase {
* protected readonly compilerName = 'R3FCompiler';
* // getRequiredCapability() returns '/compile/web3d/r3f' automatically
* }
*
* // Override: explicit namespace
* class CustomCompiler extends CompilerBase {
* protected readonly compilerName = 'CustomCompiler';
* protected getRequiredCapability(): string | undefined {
* return '/compile/web3d/r3f';
* }
* }
* ```
*/
protected getRequiredCapability(): string | undefined {
const ansName = COMPILER_CLASS_TO_ANS_NAME[this.compilerName];
if (ansName && isValidCompilerName(ansName)) {
return COMPILER_ANS_MAP[ansName];
}
// Warn when a compiler subclass is missing from the ANS map — UCAN capability
// checks will be skipped silently for this compiler until it is registered.
if (process.env['NODE_ENV'] !== 'test') {
console.warn(
`[CompilerBase] Compiler '${this.compilerName}' has no ANS namespace entry. ` +
`Add it to COMPILER_CLASS_TO_ANS_NAME to enable UCAN capability enforcement.`