typespec_rs 0.4.3

A Rust implementation of the TypeSpec type system — parser, checker, and emitter
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
//! @typespec/rest - REST API Decorators and Resource Types
//!
//! Ported from TypeSpec packages/rest
//!
//! Provides decorators for REST API modeling:
//! - `@autoRoute` - Auto-generate route from resource keys
//! - `@segment` - Define URL path segment
//! - `@segmentOf` - Get URL segment of a model
//! - `@actionSeparator` - Define action separator in routes
//! - `@resource` - Mark model as a resource type
//! - `@parentResource` - Define parent resource relationship
//! - `@readsResource`, `@createsResource`, etc. - CRUD operation decorators
//! - `@action`, `@collectionAction` - Custom action decorators
//! - `@copyResourceKeyParameters` - Copy key parameters
//!
//! Also provides:
//! - `ResourceLocation<T>` scalar type
//!
//! ## Helper Functions
//! - `is_auto_route(state, target)` - Check if target has @autoRoute
//! - `get_segment(state, target)` - Get the segment for a target
//! - `is_resource(state, target)` - Check if a model is a resource type
//! - `get_parent_resource(state, target)` - Get parent resource
//! - `is_key(state, target)` - Check if a property is a resource key
//!
//! Depends on @typespec/http

use crate::checker::types::TypeId;
use crate::diagnostics::{DiagnosticDefinition, DiagnosticMap};
use crate::state_accessors::StateAccessors;
use std::collections::HashMap;

// ============================================================================
// Diagnostic codes
// ============================================================================

/// Diagnostic: Cannot copy keys from non-key type
pub const DIAG_NOT_KEY_TYPE: &str = "not-key-type";
/// Diagnostic: Resource missing @key decorator
pub const DIAG_RESOURCE_MISSING_KEY: &str = "resource-missing-key";
/// Diagnostic: Resource missing @error decorator
pub const DIAG_RESOURCE_MISSING_ERROR: &str = "resource-missing-error";
/// Diagnostic: Duplicate key on resource
pub const DIAG_DUPLICATE_KEY: &str = "duplicate-key";
/// Diagnostic: Key name conflicts with parent/child
pub const DIAG_DUPLICATE_PARENT_KEY: &str = "duplicate-parent-key";
/// Diagnostic: Action name cannot be empty
pub const DIAG_INVALID_ACTION_NAME: &str = "invalid-action-name";
/// Diagnostic: Shared route needs explicit action name
pub const DIAG_SHARED_ROUTE_UNSPECIFIED_ACTION_NAME: &str = "shared-route-unspecified-action-name";
/// Diagnostic: Circular parent resource
pub const DIAG_CIRCULAR_PARENT_RESOURCE: &str = "circular-parent-resource";

// ============================================================================
// State keys (fully qualified with namespace)
// ============================================================================

/// State key for @autoRoute decorator
pub const STATE_AUTO_ROUTE: &str = "TypeSpec.Rest.autoRoute";
/// State key for @segment decorator
pub const STATE_SEGMENT: &str = "TypeSpec.Rest.segment";
/// State key for @resource decorator
pub const STATE_RESOURCE: &str = "TypeSpec.Rest.resource";
/// State key for @parentResource decorator
pub const STATE_PARENT_RESOURCE: &str = "TypeSpec.Rest.parentResource";
/// State key for @key decorator
pub const STATE_KEY: &str = "TypeSpec.Rest.key";
/// State key for action type tracking
pub const STATE_ACTION_TYPE: &str = "TypeSpec.Rest.actionType";
/// State key for @segmentOf decorator
pub const STATE_SEGMENT_OF: &str = "TypeSpec.Rest.segmentOf";
/// State key for @actionSeparator decorator
pub const STATE_ACTION_SEPARATOR: &str = "TypeSpec.Rest.actionSeparator";
/// State key for resource operation decorators
pub const STATE_RESOURCE_OPERATION: &str = "TypeSpec.Rest.resourceOperation";
/// State key for @actionSegment decorator (private)
pub const STATE_ACTION_SEGMENT: &str = "TypeSpec.Rest.actionSegment";
/// State key for @resourceLocation decorator (private)
pub const STATE_RESOURCE_LOCATION: &str = "TypeSpec.Rest.resourceLocation";
/// State key for @resourceTypeForKeyParam decorator (private)
pub const STATE_RESOURCE_TYPE_FOR_KEY_PARAM: &str = "TypeSpec.Rest.resourceTypeForKeyParam";
/// State key for @copyResourceKeyParameters decorator
pub const STATE_COPY_RESOURCE_KEY_PARAMS: &str = "TypeSpec.Rest.copyResourceKeyParameters";
/// State key for resource type key mapping
pub const STATE_RESOURCE_TYPE_KEY: &str = "TypeSpec.Rest.resourceTypeKey";

/// Namespace for REST types
pub const REST_NAMESPACE: &str = "TypeSpec.Rest";

// ============================================================================
// Resource operation kinds
// ============================================================================

/// Kinds of resource operations
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ResourceOperationKind {
    /// Read operation
    Reads,
    /// Create operation
    Creates,
    /// Create or replace operation
    CreatesOrReplaces,
    /// Create or update operation
    CreatesOrUpdates,
    /// Update operation
    Updates,
    /// Delete operation
    Deletes,
    /// List operation
    Lists,
}

impl ResourceOperationKind {
    /// Get the decorator name for this operation kind
    pub fn decorator_name(&self) -> &'static str {
        match self {
            ResourceOperationKind::Reads => "readsResource",
            ResourceOperationKind::Creates => "createsResource",
            ResourceOperationKind::CreatesOrReplaces => "createsOrReplacesResource",
            ResourceOperationKind::CreatesOrUpdates => "createsOrUpdatesResource",
            ResourceOperationKind::Updates => "updatesResource",
            ResourceOperationKind::Deletes => "deletesResource",
            ResourceOperationKind::Lists => "listsResource",
        }
    }
}

// ============================================================================
// Action type
// ============================================================================

/// Type of action (item-scoped or collection-scoped)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ActionType {
    /// Item-scoped action (e.g., /pets/{petId}/my-action)
    ItemAction,
    /// Collection-scoped action (e.g., /pets/my-action)
    CollectionAction,
}

// ============================================================================
// Action separator
// ============================================================================

string_enum! {
    /// Separator between action segment and the rest of the URL
    pub enum ActionSeparator {
        /// Slash separator: /
        Slash => "/",
        /// Colon separator: :
        Colon => ":",
        /// Slash-colon separator: /:
        SlashColon => "/:",
    }
}

// ============================================================================
// Action details
// ============================================================================

/// Details about an action decorator.
/// Ported from TS ActionDetails.
#[derive(Debug, Clone)]
pub struct ActionDetails {
    /// The kind of action (automatic name or explicit)
    pub kind: ActionNameKind,
    /// The resource type for collection actions
    pub resource_type: Option<TypeId>,
}

string_enum! {
    /// Whether the action name was automatically derived or explicitly provided.
    pub enum ActionNameKind {
        /// Name was automatically derived from operation name
        Automatic => "automatic",
        /// Name was explicitly provided in decorator argument
        Explicit => "explicit",
    }
}

// ============================================================================
// Resource key information
// ============================================================================

/// Information about a resource key property.
/// Ported from TS ResourceKey.
#[derive(Debug, Clone, PartialEq)]
pub struct ResourceKey {
    /// The resource type that owns the key
    pub resource_type: TypeId,
    /// The key property
    pub key_property: TypeId,
}

// ============================================================================
// Decorator implementations
// ============================================================================

flag_decorator!(apply_auto_route, is_auto_route, STATE_AUTO_ROUTE);
string_decorator!(apply_segment, get_segment, STATE_SEGMENT);

string_decorator!(apply_resource, get_resource_collection_name, STATE_RESOURCE);

/// Check if a model is a resource type.
pub fn is_resource(state: &StateAccessors, target: TypeId) -> bool {
    state.get_state(STATE_RESOURCE, target).is_some()
}

typeid_decorator!(
    apply_parent_resource,
    get_parent_resource,
    STATE_PARENT_RESOURCE
);

flag_decorator!(apply_key, is_key, STATE_KEY);

/// Implementation of the `@action` decorator.
/// Marks an operation as an item-scoped action.
pub fn apply_action(state: &mut StateAccessors, target: TypeId, name: Option<&str>) {
    let kind = if name.is_some() {
        ActionNameKind::Explicit
    } else {
        ActionNameKind::Automatic
    };
    let value = format!("action:{}:{}", kind.as_str(), name.unwrap_or(""));
    state.set_state(STATE_ACTION_TYPE, target, value);
}

/// Implementation of the `@collectionAction` decorator.
/// Marks an operation as a collection-scoped action.
pub fn apply_collection_action(
    state: &mut StateAccessors,
    target: TypeId,
    resource_type: TypeId,
    name: Option<&str>,
) {
    let kind = if name.is_some() {
        ActionNameKind::Explicit
    } else {
        ActionNameKind::Automatic
    };
    let value = format!(
        "collectionAction:{}:{}:{}",
        kind.as_str(),
        resource_type,
        name.unwrap_or("")
    );
    state.set_state(STATE_ACTION_TYPE, target, value);
}

/// Get action details for an operation.
pub fn get_action_details(state: &StateAccessors, target: TypeId) -> Option<ActionDetails> {
    state.get_state(STATE_ACTION_TYPE, target).and_then(|s| {
        let parts: Vec<&str> = s.splitn(4, ':').collect();
        if parts.len() < 2 {
            return None;
        }
        match parts[0] {
            "action" => Some(ActionDetails {
                kind: ActionNameKind::parse_str(parts[1])?,
                resource_type: None,
            }),
            "collectionAction" => {
                let resource_type = parts.get(2).and_then(|s| s.parse::<u32>().ok());
                Some(ActionDetails {
                    kind: ActionNameKind::parse_str(parts[1])?,
                    resource_type,
                })
            }
            _ => None,
        }
    })
}

// ============================================================================
// @segmentOf decorator
// ============================================================================

typeid_decorator!(apply_segment_of, get_segment_of, STATE_SEGMENT_OF);

// ============================================================================
// @actionSeparator decorator
// ============================================================================

/// Apply @actionSeparator decorator.
/// Ported from TS $actionSeparator().
pub fn apply_action_separator(
    state: &mut StateAccessors,
    target: TypeId,
    separator: ActionSeparator,
) {
    state.set_state(
        STATE_ACTION_SEPARATOR,
        target,
        separator.as_str().to_string(),
    );
}

/// Get the action separator for a target.
/// Ported from TS getActionSeparator().
pub fn get_action_separator(state: &StateAccessors, target: TypeId) -> Option<ActionSeparator> {
    state
        .get_state(STATE_ACTION_SEPARATOR, target)
        .and_then(ActionSeparator::parse_str)
}

// ============================================================================
// Resource operation decorators
// Ported from TS $readsResource, $createsResource, etc.
// ============================================================================

/// Resource operation data stored in state.
/// Format: "kind::resourceTypeId"
#[derive(Debug, Clone, PartialEq)]
pub struct ResourceOperation {
    /// The kind of resource operation
    pub kind: ResourceOperationKind,
    /// The resource type TypeId
    pub resource_type: TypeId,
}

/// Set resource operation for an operation.
/// Ported from TS setResourceOperation().
pub fn set_resource_operation(
    state: &mut StateAccessors,
    target: TypeId,
    kind: ResourceOperationKind,
    resource_type: TypeId,
) {
    let value = format!("{}::{}", kind.decorator_name(), resource_type);
    state.set_state(STATE_RESOURCE_OPERATION, target, value);
}

/// Get resource operation for an operation.
/// Ported from TS getResourceOperation().
pub fn get_resource_operation(state: &StateAccessors, target: TypeId) -> Option<ResourceOperation> {
    state
        .get_state(STATE_RESOURCE_OPERATION, target)
        .and_then(|s| {
            let parts: Vec<&str> = s.splitn(2, "::").collect();
            if parts.len() != 2 {
                return None;
            }
            let kind = ResourceOperationKind::from_decorator_name(parts[0])?;
            let resource_type = parts[1].parse::<TypeId>().ok()?;
            Some(ResourceOperation {
                kind,
                resource_type,
            })
        })
}

impl ResourceOperationKind {
    /// Parse from decorator name string
    pub fn from_decorator_name(name: &str) -> Option<Self> {
        match name {
            "readsResource" => Some(ResourceOperationKind::Reads),
            "createsResource" => Some(ResourceOperationKind::Creates),
            "createsOrReplacesResource" => Some(ResourceOperationKind::CreatesOrReplaces),
            "createsOrUpdatesResource" => Some(ResourceOperationKind::CreatesOrUpdates),
            "updatesResource" => Some(ResourceOperationKind::Updates),
            "deletesResource" => Some(ResourceOperationKind::Deletes),
            "listsResource" => Some(ResourceOperationKind::Lists),
            _ => None,
        }
    }
}

macro_rules! define_resource_op {
    ($name:ident, $kind:expr) => {
        pub fn $name(state: &mut StateAccessors, target: TypeId, resource_type: TypeId) {
            set_resource_operation(state, target, $kind, resource_type);
        }
    };
}

define_resource_op!(apply_reads_resource, ResourceOperationKind::Reads);
define_resource_op!(apply_creates_resource, ResourceOperationKind::Creates);
define_resource_op!(
    apply_creates_or_replaces_resource,
    ResourceOperationKind::CreatesOrReplaces
);
define_resource_op!(
    apply_creates_or_updates_resource,
    ResourceOperationKind::CreatesOrUpdates
);
define_resource_op!(apply_updates_resource, ResourceOperationKind::Updates);
define_resource_op!(apply_deletes_resource, ResourceOperationKind::Deletes);
define_resource_op!(apply_lists_resource, ResourceOperationKind::Lists);

/// Check if an operation is a list operation.
/// Ported from TS isListOperation().
pub fn is_list_operation(state: &StateAccessors, target: TypeId) -> bool {
    get_resource_operation(state, target)
        .map(|op| op.kind == ResourceOperationKind::Lists)
        .unwrap_or(false)
}

// ============================================================================
// @actionSegment decorator (private)
// ============================================================================

/// Apply @actionSegment decorator (private).
/// Ported from TS Private.$actionSegment().
pub fn apply_action_segment(state: &mut StateAccessors, target: TypeId, value: &str) {
    state.set_state(STATE_ACTION_SEGMENT, target, value.to_string());
}

/// Get @actionSegment value.
/// Ported from TS getActionSegment().
pub fn get_action_segment(state: &StateAccessors, target: TypeId) -> Option<String> {
    state
        .get_state(STATE_ACTION_SEGMENT, target)
        .map(|s| s.to_string())
}

// ============================================================================
// @resourceLocation decorator (private)
// ============================================================================

typeid_decorator!(
    apply_resource_location,
    get_resource_location_type,
    STATE_RESOURCE_LOCATION
);

// ============================================================================
// @resourceTypeForKeyParam decorator (private)
// ============================================================================

typeid_decorator!(
    apply_resource_type_for_key_param,
    get_resource_type_for_key_param,
    STATE_RESOURCE_TYPE_FOR_KEY_PARAM
);

// ============================================================================
// @copyResourceKeyParameters decorator
// ============================================================================

/// Apply @copyResourceKeyParameters decorator.
/// Ported from TS $copyResourceKeyParameters().
/// Filter is stored as optional string.
pub fn apply_copy_resource_key_parameters(
    state: &mut StateAccessors,
    target: TypeId,
    filter: Option<&str>,
) {
    state.set_state(
        STATE_COPY_RESOURCE_KEY_PARAMS,
        target,
        filter.unwrap_or("").to_string(),
    );
}

/// Get the filter for @copyResourceKeyParameters.
pub fn get_copy_resource_key_parameters_filter(
    state: &StateAccessors,
    target: TypeId,
) -> Option<String> {
    state
        .get_state(STATE_COPY_RESOURCE_KEY_PARAMS, target)
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
}

// ============================================================================
// Resource type key mapping
// Ported from TS setResourceTypeKey/getResourceTypeKey
// ============================================================================

/// Set the resource type key for a model.
/// Ported from TS setResourceTypeKey().
pub fn set_resource_type_key(state: &mut StateAccessors, target: TypeId, key: &ResourceKey) {
    let value = format!("{}::{}", key.resource_type, key.key_property);
    state.set_state(STATE_RESOURCE_TYPE_KEY, target, value);
}

/// Get the resource type key for a model.
/// Ported from TS getResourceTypeKey().
pub fn get_resource_type_key(state: &StateAccessors, target: TypeId) -> Option<ResourceKey> {
    state
        .get_state(STATE_RESOURCE_TYPE_KEY, target)
        .and_then(|s| {
            let parts: Vec<&str> = s.split("::").collect();
            if parts.len() == 2 {
                let resource_type = parts[0].parse::<TypeId>().ok()?;
                let key_property = parts[1].parse::<TypeId>().ok()?;
                Some(ResourceKey {
                    resource_type,
                    key_property,
                })
            } else {
                None
            }
        })
}

// ============================================================================
// Library creation
// ============================================================================

/// Create the @typespec/rest library diagnostic map.
/// Ported from TS $lib definition in lib.ts.
pub fn create_rest_library() -> DiagnosticMap {
    HashMap::from([
        (
            DIAG_NOT_KEY_TYPE.to_string(),
            DiagnosticDefinition::error(
                "Cannot copy keys from a non-key type (KeysOf<T> or ParentKeysOf<T>)",
            ),
        ),
        (
            DIAG_RESOURCE_MISSING_KEY.to_string(),
            DiagnosticDefinition::error(
                "Type '{modelName}' is used as a resource and therefore must have a key. Use @key to designate a property as the key.",
            ),
        ),
        (
            DIAG_RESOURCE_MISSING_ERROR.to_string(),
            DiagnosticDefinition::error(
                "Type '{modelName}' is used as an error and therefore must have the @error decorator applied.",
            ),
        ),
        (
            DIAG_DUPLICATE_KEY.to_string(),
            DiagnosticDefinition::error("More than one key found on model type {resourceName}"),
        ),
        (
            DIAG_DUPLICATE_PARENT_KEY.to_string(),
            DiagnosticDefinition::error(
                "Resource type '{resourceName}' has a key property named '{keyName}' which conflicts with the key name of a parent or child resource.",
            ),
        ),
        (
            DIAG_INVALID_ACTION_NAME.to_string(),
            DiagnosticDefinition::error("Action name cannot be empty string."),
        ),
        (
            DIAG_SHARED_ROUTE_UNSPECIFIED_ACTION_NAME.to_string(),
            DiagnosticDefinition::error(
                "An operation marked as '@sharedRoute' must have an explicit collection action name passed to '{decoratorName}'.",
            ),
        ),
        (
            DIAG_CIRCULAR_PARENT_RESOURCE.to_string(),
            DiagnosticDefinition::error("Resource has a parent cycle ({cycle})"),
        ),
    ])
}

// ============================================================================
// TSP Sources
// ============================================================================

/// The TypeSpec source for the REST library decorators
pub const REST_DECORATORS_TSP: &str = r#"
namespace TypeSpec.Rest;

using TypeSpec.Reflection;

/**
 * This interface or operation should resolve its route automatically.
 */
extern dec autoRoute(target: Interface | Operation);

/**
 * Defines the preceding path segment for a @path parameter in auto-generated routes.
 *
 * @param name Segment that will be inserted into the operation route before the path parameter's name field.
 */
extern dec segment(target: Model | ModelProperty | Operation, name: valueof string);

/**
 * Returns the URL segment of a given model if it has @segment and @key decorator.
 * @param type Target model
 */
extern dec segmentOf(target: Operation, type: Model);

/**
 * Defines the separator string that is inserted before the action name in auto-generated routes for actions.
 *
 * @param seperator Seperator seperating the action segment from the rest of the url
 */
extern dec actionSeparator(
  target: Operation | Interface | Namespace,
  seperator: valueof "/" | ":" | "/:"
);

/**
 * Mark this model as a resource type with a name.
 *
 * @param collectionName type's collection name
 */
extern dec resource(target: Model, collectionName: valueof string);

/**
 * Mark model as a child of the given parent resource.
 * @param parent Parent model.
 */
extern dec parentResource(target: Model, parent: Model);

/**
 * Specify that this is a Read operation for a given resource.
 * @param resourceType Resource marked with @resource
 */
extern dec readsResource(target: Operation, resourceType: Model);

/**
 * Specify that this is a Create operation for a given resource.
 * @param resourceType Resource marked with @resource
 */
extern dec createsResource(target: Operation, resourceType: Model);

/**
 * Specify that this is a CreateOrReplace operation for a given resource.
 * @param resourceType Resource marked with @resource
 */
extern dec createsOrReplacesResource(target: Operation, resourceType: Model);

/**
 * Specify that this is a CreatesOrUpdate operation for a given resource.
 * @param resourceType Resource marked with @resource
 */
extern dec createsOrUpdatesResource(target: Operation, resourceType: Model);

/**
 * Specify that this is a Update operation for a given resource.
 * @param resourceType Resource marked with @resource
 */
extern dec updatesResource(target: Operation, resourceType: Model);

/**
 * Specify that this is a Delete operation for a given resource.
 * @param resourceType Resource marked with @resource
 */
extern dec deletesResource(target: Operation, resourceType: Model);

/**
 * Specify that this is a List operation for a given resource.
 * @param resourceType Resource marked with @resource
 */
extern dec listsResource(target: Operation, resourceType: Model);

/**
 * Specify this operation is an action. (Scoped to a resource item /pets/{petId}/my-action)
 * @param name Name of the action. If not specified, the name of the operation will be used.
 */
extern dec action(target: Operation, name?: valueof string);

/**
 * Specify this operation is a collection action. (Scoped to a resource, /pets/my-action)
 * @param resourceType Resource marked with @resource
 * @param name Name of the action. If not specified, the name of the operation will be used.
 */
extern dec collectionAction(target: Operation, resourceType: Model, name?: valueof string);

/**
 * Copy the resource key parameters on the model
 * @param filter Filter to exclude certain properties.
 */
extern dec copyResourceKeyParameters(target: Model, filter?: valueof string);

namespace Private {
  extern dec resourceLocation(target: string, resourceType: Model);
  extern dec validateHasKey(target: unknown, value: unknown);
  extern dec validateIsError(target: unknown, value: unknown);
  extern dec actionSegment(target: Operation, value: valueof string);
  extern dec resourceTypeForKeyParam(entity: ModelProperty, resourceType: Model);
}
"#;

/// The TypeSpec source for the REST library types
pub const REST_TSP: &str = r#"
import "@typespec/http";
import "./rest-decorators.tsp";
import "./resource.tsp";
import "../dist/src/tsp-index.js";

namespace TypeSpec.Rest;

/**
 * A URL that points to a resource.
 * @template Resource The type of resource that the URL points to.
 */
@doc("The location of an instance of {name}", Resource)
@Private.resourceLocation(Resource)
scalar ResourceLocation<Resource extends {}> extends url;
"#;

/// The TypeSpec source for the REST library resource templates
/// Ported from TS packages/rest/lib/resource.tsp
pub const RESOURCE_TSP: &str = r#"
namespace TypeSpec.Rest.Resource;

using Http;

@doc("The default error response for resource operations.")
model ResourceError {
  code: int32;
  message: string;
}

@doc("Dynamically gathers keys of the model type Resource.")
@copyResourceKeyParameters
@friendlyName("{name}Key", Resource)
model KeysOf<Resource> {}

@doc("Dynamically gathers parent keys of the model type Resource.")
@copyResourceKeyParameters("parent")
@friendlyName("{name}ParentKey", Resource)
model ParentKeysOf<Resource> {}

@doc("Represents operation parameters for resource Resource.")
model ResourceParameters<Resource extends {}> {
  ...KeysOf<Resource>;
}

@doc("Represents collection operation parameters for resource Resource.")
model ResourceCollectionParameters<Resource extends {}> {
  ...ParentKeysOf<Resource>;
}

@doc("Resource create operation completed successfully.")
model ResourceCreatedResponse<Resource> {
  ...CreatedResponse;
  @bodyRoot body: Resource;
}

@friendlyName("{name}Update", Resource)
model ResourceCreateOrUpdateModel<Resource extends {}>
  is OptionalProperties<UpdateableProperties<DefaultKeyVisibility<Resource, Lifecycle.Read>>>;

@friendlyName("{name}Create", Resource)
@withVisibility(Lifecycle.Create)
model ResourceCreateModel<Resource extends {}> is DefaultKeyVisibility<Resource, Lifecycle.Read>;

@doc("Resource deleted successfully.")
model ResourceDeletedResponse {
  @statusCode
  _: 200;
}

@doc("Paged response of {name} items", Resource)
@friendlyName("{name}CollectionWithNextLink", Resource)
model CollectionWithNextLink<Resource extends {}> {
  @pageItems
  value: Resource[];
  @nextLink
  nextLink?: ResourceLocation<Resource>;
}
"#;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rest_namespace() {
        assert_eq!(REST_NAMESPACE, "TypeSpec.Rest");
    }

    #[test]
    fn test_create_rest_library() {
        let diags = create_rest_library();
        assert_eq!(diags.len(), 8);
        let codes: Vec<&str> = diags.keys().map(|code| code.as_str()).collect();
        assert!(codes.contains(&DIAG_RESOURCE_MISSING_KEY));
        assert!(codes.contains(&DIAG_CIRCULAR_PARENT_RESOURCE));
        assert!(codes.contains(&DIAG_DUPLICATE_KEY));
    }

    #[test]
    fn test_resource_operation_kinds() {
        assert_eq!(
            ResourceOperationKind::Reads.decorator_name(),
            "readsResource"
        );
        assert_eq!(
            ResourceOperationKind::Creates.decorator_name(),
            "createsResource"
        );
        assert_eq!(
            ResourceOperationKind::Deletes.decorator_name(),
            "deletesResource"
        );
        assert_eq!(
            ResourceOperationKind::Lists.decorator_name(),
            "listsResource"
        );
    }

    #[test]
    fn test_action_separator() {
        assert_eq!(ActionSeparator::Slash.as_str(), "/");
        assert_eq!(ActionSeparator::Colon.as_str(), ":");
        assert_eq!(ActionSeparator::SlashColon.as_str(), "/:");

        assert_eq!(
            ActionSeparator::parse_str("/"),
            Some(ActionSeparator::Slash)
        );
        assert_eq!(
            ActionSeparator::parse_str(":"),
            Some(ActionSeparator::Colon)
        );
        assert_eq!(
            ActionSeparator::parse_str("/:"),
            Some(ActionSeparator::SlashColon)
        );
        assert_eq!(ActionSeparator::parse_str("x"), None);
    }

    #[test]
    fn test_decorators_tsp_not_empty() {
        assert!(!REST_DECORATORS_TSP.is_empty());
        assert!(REST_DECORATORS_TSP.contains("autoRoute"));
        assert!(REST_DECORATORS_TSP.contains("segment"));
        assert!(REST_DECORATORS_TSP.contains("resource"));
        assert!(REST_DECORATORS_TSP.contains("readsResource"));
        assert!(REST_DECORATORS_TSP.contains("action"));
        assert!(REST_DECORATORS_TSP.contains("collectionAction"));
    }

    #[test]
    fn test_rest_tsp_not_empty() {
        assert!(!REST_TSP.is_empty());
        assert!(REST_TSP.contains("ResourceLocation"));
    }

    #[test]
    fn test_resource_tsp_not_empty() {
        assert!(!RESOURCE_TSP.is_empty());
        assert!(RESOURCE_TSP.contains("ResourceError"));
        assert!(RESOURCE_TSP.contains("KeysOf"));
        assert!(RESOURCE_TSP.contains("ResourceParameters"));
        assert!(RESOURCE_TSP.contains("ResourceCreateModel"));
        assert!(RESOURCE_TSP.contains("CollectionWithNextLink"));
    }

    #[test]
    fn test_is_auto_route() {
        let mut state = StateAccessors::new();
        assert!(!is_auto_route(&state, 1));
        apply_auto_route(&mut state, 1);
        assert!(is_auto_route(&state, 1));
        assert!(!is_auto_route(&state, 2));
    }

    #[test]
    fn test_get_segment() {
        let mut state = StateAccessors::new();
        assert_eq!(get_segment(&state, 1), None);
        apply_segment(&mut state, 1, "pets");
        assert_eq!(get_segment(&state, 1), Some("pets".to_string()));
    }

    #[test]
    fn test_is_resource() {
        let mut state = StateAccessors::new();
        assert!(!is_resource(&state, 1));
        apply_resource(&mut state, 1, "pets");
        assert!(is_resource(&state, 1));
        assert_eq!(
            get_resource_collection_name(&state, 1),
            Some("pets".to_string())
        );
    }

    #[test]
    fn test_parent_resource() {
        let mut state = StateAccessors::new();
        assert_eq!(get_parent_resource(&state, 1), None);
        apply_parent_resource(&mut state, 1, 5);
        assert_eq!(get_parent_resource(&state, 1), Some(5));
    }

    #[test]
    fn test_is_key() {
        let mut state = StateAccessors::new();
        assert!(!is_key(&state, 1));
        apply_key(&mut state, 1);
        assert!(is_key(&state, 1));
    }

    #[test]
    fn test_apply_action() {
        let mut state = StateAccessors::new();
        apply_action(&mut state, 1, None);
        let details = get_action_details(&state, 1);
        assert!(details.is_some());
        let details = details.unwrap();
        assert_eq!(details.kind, ActionNameKind::Automatic);
        assert!(details.resource_type.is_none());

        apply_action(&mut state, 2, Some("customAction"));
        let details = get_action_details(&state, 2);
        assert!(details.is_some());
        assert_eq!(details.unwrap().kind, ActionNameKind::Explicit);
    }

    #[test]
    fn test_apply_collection_action() {
        let mut state = StateAccessors::new();
        apply_collection_action(&mut state, 1, 10, Some("list"));
        let details = get_action_details(&state, 1);
        assert!(details.is_some());
        let details = details.unwrap();
        assert_eq!(details.kind, ActionNameKind::Explicit);
        assert_eq!(details.resource_type, Some(10));
    }

    #[test]
    fn test_segment_of() {
        let mut state = StateAccessors::new();
        assert_eq!(get_segment_of(&state, 1), None);
        apply_segment_of(&mut state, 1, 42);
        assert_eq!(get_segment_of(&state, 1), Some(42));
    }

    #[test]
    fn test_action_separator_decorator() {
        let mut state = StateAccessors::new();
        assert_eq!(get_action_separator(&state, 1), None);
        apply_action_separator(&mut state, 1, ActionSeparator::Slash);
        assert_eq!(
            get_action_separator(&state, 1),
            Some(ActionSeparator::Slash)
        );
        apply_action_separator(&mut state, 2, ActionSeparator::Colon);
        assert_eq!(
            get_action_separator(&state, 2),
            Some(ActionSeparator::Colon)
        );
    }

    #[test]
    fn test_resource_operation() {
        let mut state = StateAccessors::new();
        assert_eq!(get_resource_operation(&state, 1), None);
        apply_reads_resource(&mut state, 1, 10);
        let op = get_resource_operation(&state, 1).unwrap();
        assert_eq!(op.kind, ResourceOperationKind::Reads);
        assert_eq!(op.resource_type, 10);
    }

    #[test]
    fn test_creates_resource() {
        let mut state = StateAccessors::new();
        apply_creates_resource(&mut state, 1, 20);
        let op = get_resource_operation(&state, 1).unwrap();
        assert_eq!(op.kind, ResourceOperationKind::Creates);
        assert_eq!(op.resource_type, 20);
    }

    #[test]
    fn test_deletes_resource() {
        let mut state = StateAccessors::new();
        apply_deletes_resource(&mut state, 1, 30);
        let op = get_resource_operation(&state, 1).unwrap();
        assert_eq!(op.kind, ResourceOperationKind::Deletes);
    }

    #[test]
    fn test_lists_resource_is_list() {
        let mut state = StateAccessors::new();
        assert!(!is_list_operation(&state, 1));
        apply_lists_resource(&mut state, 1, 10);
        assert!(is_list_operation(&state, 1));
    }

    #[test]
    fn test_action_segment() {
        let mut state = StateAccessors::new();
        assert_eq!(get_action_segment(&state, 1), None);
        apply_action_segment(&mut state, 1, "customAction");
        assert_eq!(
            get_action_segment(&state, 1),
            Some("customAction".to_string())
        );
    }

    #[test]
    fn test_resource_location() {
        let mut state = StateAccessors::new();
        assert_eq!(get_resource_location_type(&state, 1), None);
        apply_resource_location(&mut state, 1, 50);
        assert_eq!(get_resource_location_type(&state, 1), Some(50));
    }

    #[test]
    fn test_resource_type_for_key_param() {
        let mut state = StateAccessors::new();
        assert_eq!(get_resource_type_for_key_param(&state, 1), None);
        apply_resource_type_for_key_param(&mut state, 1, 99);
        assert_eq!(get_resource_type_for_key_param(&state, 1), Some(99));
    }

    #[test]
    fn test_copy_resource_key_parameters() {
        let mut state = StateAccessors::new();
        apply_copy_resource_key_parameters(&mut state, 1, None);
        assert_eq!(get_copy_resource_key_parameters_filter(&state, 1), None);
        apply_copy_resource_key_parameters(&mut state, 2, Some("excludeId"));
        assert_eq!(
            get_copy_resource_key_parameters_filter(&state, 2),
            Some("excludeId".to_string())
        );
    }

    #[test]
    fn test_resource_type_key() {
        let mut state = StateAccessors::new();
        assert_eq!(get_resource_type_key(&state, 1), None);
        set_resource_type_key(
            &mut state,
            1,
            &ResourceKey {
                resource_type: 5,
                key_property: 10,
            },
        );
        let key = get_resource_type_key(&state, 1).unwrap();
        assert_eq!(key.resource_type, 5);
        assert_eq!(key.key_property, 10);
    }

    #[test]
    fn test_resource_operation_kind_from_decorator_name() {
        assert_eq!(
            ResourceOperationKind::from_decorator_name("readsResource"),
            Some(ResourceOperationKind::Reads)
        );
        assert_eq!(
            ResourceOperationKind::from_decorator_name("createsResource"),
            Some(ResourceOperationKind::Creates)
        );
        assert_eq!(ResourceOperationKind::from_decorator_name("unknown"), None);
    }
}