|
| 1 | +import 'package:cedar/ast.dart'; |
| 2 | +import 'package:celest_cloud_core/src/model/resource_type.dart'; |
| 3 | + |
| 4 | +typedef _ResourceNameInfo = ({ |
| 5 | + ResourceType type, |
| 6 | + EntityUid uid, |
| 7 | + List<EntityUid> parents, |
| 8 | +}); |
| 9 | + |
| 10 | +/// A resource name in Celest Cloud. |
| 11 | +/// |
| 12 | +/// Example: `organizations/123/projects/456/environments/789` |
| 13 | +extension type ResourceName(_ResourceNameInfo _info) { |
| 14 | + /// Parses a resource name string into a [ResourceName] object. |
| 15 | + factory ResourceName.parse(String name) { |
| 16 | + final segments = name.split('/').reversed.toList(); |
| 17 | + if (segments.length < 2 || segments.length % 2 != 0) { |
| 18 | + throw ArgumentError('Invalid resource name: $name'); |
| 19 | + } |
| 20 | + |
| 21 | + (ResourceType, String)? uid; |
| 22 | + final parents = <EntityUid>[]; |
| 23 | + for (var i = 0; i < segments.length; i += 2) { |
| 24 | + final type = segments[i + 1]; |
| 25 | + final id = segments[i]; |
| 26 | + if (type.isEmpty || id.isEmpty) { |
| 27 | + throw ArgumentError('Invalid resource name: $name'); |
| 28 | + } |
| 29 | + final resourceType = ResourceType.fromPatternType(type); |
| 30 | + if (uid == null) { |
| 31 | + uid = (resourceType, id); |
| 32 | + } else { |
| 33 | + parents.add(resourceType.uid(id)); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + final (resourceType, id) = uid!; |
| 38 | + return ResourceName(( |
| 39 | + type: resourceType, |
| 40 | + uid: resourceType.uid(id), |
| 41 | + parents: parents, |
| 42 | + )); |
| 43 | + } |
| 44 | + |
| 45 | + /// A map of resource pattern types to their Cedar entity types. |
| 46 | + static const Map<String, EntityTypeName> entityTypes = { |
| 47 | + 'operations': EntityTypeName('Celest::Operation'), |
| 48 | + 'users': EntityTypeName('Celest::User'), |
| 49 | + 'sessions': EntityTypeName('Celest::Session'), |
| 50 | + 'projects': EntityTypeName('Celest::Project'), |
| 51 | + 'organizations': EntityTypeName('Celest::Organization'), |
| 52 | + 'environments': EntityTypeName('Celest::Project::Environment'), |
| 53 | + }; |
| 54 | + |
| 55 | + /// The resource type for this resource. |
| 56 | + ResourceType get type => _info.type; |
| 57 | + |
| 58 | + /// The unique identifier for this resource. |
| 59 | + EntityUid get uid => _info.uid; |
| 60 | + |
| 61 | + /// The list of parent resources for this resource. |
| 62 | + List<EntityUid> get parents => _info.parents; |
| 63 | +} |
0 commit comments