Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion src/Commands/TypeScriptCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,8 @@ private function collectCapabilities(DefinitionDiscoverer $discoverer): array
* - "article:view" → ["ArticlePermissions", "VIEW"]
* - "user.create" → ["UserPermissions", "CREATE"]
* - "admin" → ["Roles", "ADMIN"]
* - "article:*" → ["ArticlePermissions", "*"]
* - "*" → ["Permissions", "*"]
*
* @return array{0: string, 1: string}
*/
Expand All @@ -328,6 +330,14 @@ private function parseNameToGroupAndConst(string $name, string $defaultGroup): a
return [$defaultGroup, $constName];
}

/**
* Check if a string is a valid JavaScript/TypeScript identifier.
*/
private function isValidIdentifier(string $name): bool
{
return (bool) preg_match('/^[a-zA-Z_$][a-zA-Z0-9_$]*$/', $name);
}

/**
* Group definitions by their source class.
*
Expand Down Expand Up @@ -364,7 +374,9 @@ private function generateConstObject(string $groupName, array $items): string
$lines = ["export const {$groupName} = {"];

foreach ($items as $constName => $value) {
$lines[] = " {$constName}: \"{$value}\",";
// Quote keys that aren't valid identifiers (e.g., wildcards like "*")
$key = $this->isValidIdentifier($constName) ? $constName : "\"{$constName}\"";
$lines[] = " {$key}: \"{$value}\",";
}

$lines[] = '} as const;';
Expand Down
22 changes: 22 additions & 0 deletions tests/Feature/Commands/TypeScriptCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,28 @@
expect($content)->toContain('export type Role');
});

it('quotes wildcard permissions as valid TypeScript property keys', function () {
config(['mandate.code_first.enabled' => false]);

// Create wildcard permissions in the database
OffloadProject\Mandate\Models\Permission::create(['name' => '*']);
OffloadProject\Mandate\Models\Permission::create(['name' => 'article:*']);

$outputFile = $this->outputPath.'/mandate.ts';

$this->artisan('mandate:typescript', ['--output' => $outputFile])
->assertSuccessful();

$content = file_get_contents($outputFile);

// Wildcard keys should be quoted
expect($content)->toContain('"*": "*"');
expect($content)->toContain('"*": "article:*"');

// Should NOT contain unquoted * as a key
expect($content)->not->toMatch('/^\s+\*:/m');
});

it('uses as const for objects', function () {
$outputFile = $this->outputPath.'/mandate.ts';

Expand Down