diff --git a/README.md b/README.md index 285684a..f9c97ca 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Requires PHP 8.4+, Laravel 13, and Node.js for the Skir compiler. - Scaffold application-owned controllers and Form Requests from generated manifests. See [Scaffolding](docs/scaffolding.md). - Route procedures to attributed or invokable Laravel controllers with native dependency injection, middleware, authorization, and Form Requests. See [Routing](docs/routing.md). - Keep generated providers and manual handlers available for non-controller layouts. See [Routing](docs/routing.md#generated-procedure-providers). -- Inspect an endpoint's procedures through its opt-in Studio. See [Studio](docs/routing.md#studio). +- Browse and call an endpoint's procedures in Skir's RPC Studio, opt-in per endpoint. See [Studio](docs/routing.md#studio). - Speak the standard SkirRPC protocol, so clients generated for any Skir language can call your endpoints. See [Wire protocol](docs/protocol.md). ## Quick start diff --git a/config/skir-server.php b/config/skir-server.php index 4831f50..20070c2 100644 --- a/config/skir-server.php +++ b/config/skir-server.php @@ -5,6 +5,7 @@ return [ 'studio_enabled' => env('SKIR_SERVER_STUDIO_ENABLED', false), 'studio_query_key' => env('SKIR_SERVER_STUDIO_QUERY_KEY', 'studio'), + 'studio_app_js_url' => env('SKIR_SERVER_STUDIO_APP_JS_URL', 'https://cdn.jsdelivr.net/npm/skir-studio/dist/skir-studio-standalone.js'), 'manifests' => [ base_path('app/Skir/skirout/skir-server-manifest.json'), diff --git a/docs/routing.md b/docs/routing.md index 01e186e..9cac660 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -315,8 +315,11 @@ Studio is controlled by these settings in `config/skir-server.php`: ```php 'studio_enabled' => env('SKIR_SERVER_STUDIO_ENABLED', false), 'studio_query_key' => env('SKIR_SERVER_STUDIO_QUERY_KEY', 'studio'), +'studio_app_js_url' => env('SKIR_SERVER_STUDIO_APP_JS_URL', 'https://cdn.jsdelivr.net/npm/skir-studio/dist/skir-studio-standalone.js'), ``` +Studio is Skir's [RPC Studio](https://skir.build/docs/skirrpc#rpc-studio): a page to browse an endpoint's methods, fill in a request, send it and read the response. The endpoint serves a small HTML page that loads the Studio app from `studio_app_js_url`; point that setting at your own copy of the script when the app must not come from a CDN. + Studio is disabled by default. Enable it on an individual endpoint with `studio()`: ```php @@ -331,6 +334,14 @@ Route::skirRpc('/api/skir', [ Calling `studio()` explicitly enables Studio for that endpoint, regardless of `studio_enabled`. With the default query key, open `/api/skir?studio` with a GET request. Only the query parameter's presence matters; its value is ignored. Studio renders the procedures registered on that route. Endpoints with providers keep separate procedure lists; endpoints registered without providers all share the application-wide `SkirServer` and list the same procedures. +### Method list + +The Studio app reads the endpoint's methods from a GET request to `/api/skir?list`. The answer follows the upstream Skir services: every method with its name, number, and the type descriptors of its request and response. The list is available only while Studio is enabled for the endpoint; otherwise it answers `404`. + +The PHP runtime types carry no record names, so the names in the list are derived. A method's request and response are named `Request` and `Response`, and a nested struct or enum is named after the field or variant that holds it. Structs and enums with the same shape share one definition. These names only label the Studio forms; they do not affect the wire format. + +Studio sends its calls from the browser as `{"method": ..., "request": ...}` POST requests, with the `Authorization` header you enter in the app. Outer route middleware applies to the Studio page, the method list, and every call. + Set `studio_enabled` to `true` to enable Studio for every SkirRPC route by default. Calling `studio(false)` on a route overrides that global setting and keeps Studio disabled for that endpoint. Use `studio_query_key` to change the query parameter. For example, setting it to `skir-studio` makes the Studio URL `/api/skir?skir-studio`. diff --git a/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md b/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md index d7cc9b8..d0e5203 100644 --- a/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md +++ b/resources/boost/skills/skir-server-development/references/studio-protocol-and-testing.md @@ -6,6 +6,10 @@ Studio is disabled by default. Enable it per route with `studio()` or override a `studio(false)`. Package configuration uses `studio_enabled` and `studio_query_key`; the query key only selects the Studio response and is never access control. +Studio is the official Skir RPC Studio app, loaded from `studio_app_js_url`. It reads the endpoint's +methods from `GET ?list`, which answers `404` unless Studio is enabled, and sends calls as +readable JSON POST requests. + ```php Route::skirRpc('/api/skir', [ Skir::controller(AccountController::class), @@ -42,7 +46,7 @@ paths applicable to the change: - regressions for explicit `null`, boundary request shapes, and any corrected failure contract. Assert status, Skir error code/details, response content type/body, authorization boundary, and side -effects. For Studio, assert both rendered procedure metadata and protection on the outer route. Use +effects. For Studio, assert the `?list` method metadata and protection on the outer route. Use genuine encoded request/response bodies. When a test fails, first identify whether the mismatch belongs to route protection, method diff --git a/src/Http/Controllers/SkirRpcController.php b/src/Http/Controllers/SkirRpcController.php index ae5d215..6b466f5 100644 --- a/src/Http/Controllers/SkirRpcController.php +++ b/src/Http/Controllers/SkirRpcController.php @@ -19,14 +19,18 @@ use Skir\Server\RegisteredProcedure; use Skir\Server\Routing\SkirEndpointRegistry; use Skir\Server\SkirContext; +use Skir\Server\Studio\MethodList; use Skir\Server\Studio\StudioRenderer; use Symfony\Component\HttpFoundation\Response; final readonly class SkirRpcController { + private const string STUDIO_APP_JS_URL = 'https://cdn.jsdelivr.net/npm/skir-studio/dist/skir-studio-standalone.js'; + public function __construct( private SkirEndpointRegistry $endpoints, private StudioRenderer $studioRenderer, + private MethodList $methodList, private Container $container, private SkirMethodRequestScope $requestScope, private Router $router, @@ -37,13 +41,21 @@ public function __invoke(Request $request): Response try { $server = $this->endpoints->server($request->route()); + if ($this->isMethodListRequest($request)) { + if (! $this->studioEnabled($request)) { + abort(Response::HTTP_NOT_FOUND); + } + + return response()->json($this->methodList->toArray($server)); + } + if ($this->isStudioRequest($request)) { if (! $this->studioEnabled($request)) { abort(Response::HTTP_NOT_FOUND); } return response( - $this->studioRenderer->render($server, '/'.$request->path()), + $this->studioRenderer->render((string) config('skir-server.studio_app_js_url', self::STUDIO_APP_JS_URL)), Response::HTTP_OK, )->header('content-type', 'text/html; charset=UTF-8'); } @@ -109,6 +121,15 @@ private function procedureMiddleware(PreparedProcedure $prepared): array return $prepared->middleware; } + private function isMethodListRequest(Request $request): bool + { + if (! $this->usesQueryString($request)) { + return false; + } + + return $this->rpcBody($request) === 'list'; + } + private function isStudioRequest(Request $request): bool { if (! $this->usesQueryString($request)) { diff --git a/src/Studio/MethodList.php b/src/Studio/MethodList.php new file mode 100644 index 0000000..223791c --- /dev/null +++ b/src/Studio/MethodList.php @@ -0,0 +1,43 @@ +, + * response: array + * }> + * } + */ + public function toArray(SkirServer $server): array + { + return [ + 'methods' => array_values(array_map( + fn (RegisteredProcedure $procedure): array => [ + 'method' => $procedure->descriptor->name, + 'number' => $procedure->descriptor->number, + 'request' => (new TypeDescriptor)->describe( + $procedure->descriptor->requestType, + "{$procedure->descriptor->name}Request", + ), + 'response' => (new TypeDescriptor)->describe( + $procedure->descriptor->responseType, + "{$procedure->descriptor->name}Response", + ), + ], + $server->procedures(), + )), + ]; + } +} diff --git a/src/Studio/StudioRenderer.php b/src/Studio/StudioRenderer.php index 0896a6a..ea278c0 100644 --- a/src/Studio/StudioRenderer.php +++ b/src/Studio/StudioRenderer.php @@ -4,239 +4,30 @@ namespace Skir\Server\Studio; -use Skir\Runtime\Field; -use Skir\Runtime\MethodDescriptor; -use Skir\Runtime\Type; -use Skir\Runtime\Variant; -use Skir\Server\RegisteredProcedure; -use Skir\Server\SkirServer; - +/** + * The page that hosts the official RPC Studio app (https://skir.build/docs/skirrpc#rpc-studio). + * + * The app is one script. It reads the endpoint's method list from `?list` and calls the methods itself. + */ final class StudioRenderer { - public function render(SkirServer $server, string $endpoint): string + public function render(string $appJsUrl): string { - $metadata = [ - 'endpoint' => $endpoint, - 'methods' => array_values(array_map( - fn (RegisteredProcedure $procedure): array => $this->methodToArray($procedure->descriptor), - $server->procedures(), - )), - ]; - - $encodedMetadata = htmlspecialchars( - json_encode($metadata, JSON_THROW_ON_ERROR), - ENT_QUOTES | ENT_SUBSTITUTE, - 'UTF-8', - ); - - $methodRows = implode('', array_map( - fn (array $method): string => $this->renderMethod($method), - $metadata['methods'], - )); - - if ($methodRows === '') { - $methodRows = '

No Skir procedures are registered for this endpoint.

'; - } - - $escapedEndpoint = $this->escape($endpoint); + $escapedAppJsUrl = htmlspecialchars($appJsUrl, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); return << - - - - - Skir RPC Studio - - - -
-

Skir RPC Studio

-

{$escapedEndpoint}

- {$methodRows} -
- + + + + + RPC Studio + + + + + + HTML; } - - /** - * @return array{ - * name: string, - * number: int, - * request: array, - * response: array - * } - */ - private function methodToArray(MethodDescriptor $descriptor): array - { - return [ - 'name' => $descriptor->name, - 'number' => $descriptor->number, - 'request' => $this->typeToArray($descriptor->requestType), - 'response' => $this->typeToArray($descriptor->responseType), - ]; - } - - /** - * @return array - */ - private function typeToArray(Type $type): array - { - $payload = [ - 'kind' => $type->kind->value, - ]; - - if ($type->itemType !== null) { - $payload['item'] = $this->typeToArray($type->itemType); - } - - if ($type->fields !== []) { - $payload['fields'] = array_map( - fn (Field $field): array => $this->fieldToArray($field), - $type->fields, - ); - } - - if ($type->variants !== []) { - $payload['variants'] = array_map( - fn (Variant $variant): array => $this->variantToArray($variant), - $type->variants, - ); - } - - return $payload; - } - - /** - * @return array{name: string|null, number: int, removed: bool, type?: array} - */ - private function fieldToArray(Field $field): array - { - $payload = [ - 'name' => $field->name, - 'number' => $field->number, - 'removed' => $field->removed, - ]; - - if ($field->type !== null) { - $payload['type'] = $this->typeToArray($field->type); - } - - return $payload; - } - - /** - * @return array{name: string, number: int, payload?: array} - */ - private function variantToArray(Variant $variant): array - { - $payload = [ - 'name' => $variant->name, - 'number' => $variant->number, - ]; - - if ($variant->payloadType !== null) { - $payload['payload'] = $this->typeToArray($variant->payloadType); - } - - return $payload; - } - - /** - * @param array{ - * name: string, - * number: int, - * request: array, - * response: array - * } $method - */ - private function renderMethod(array $method): string - { - $name = $this->escape($method['name']); - $number = (string) $method['number']; - $request = $this->escape(json_encode($method['request'], JSON_THROW_ON_ERROR)); - $response = $this->escape(json_encode($method['response'], JSON_THROW_ON_ERROR)); - - return << -

{$name}

-
-
Number
-
{$number}
-
Request
-
{$request}
-
Response
-
{$response}
-
- -HTML; - } - - private function escape(string $value): string - { - return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); - } } diff --git a/src/Studio/TypeDescriptor.php b/src/Studio/TypeDescriptor.php new file mode 100644 index 0000000..a76a448 --- /dev/null +++ b/src/Studio/TypeDescriptor.php @@ -0,0 +1,185 @@ + */ + private array $recordIdsByShape = []; + + /** @var array> */ + private array $records = []; + + /** + * @return array{ + * type: array, + * records: list> + * } + */ + public function describe(Type $type, string $name): array + { + $this->recordIdsByShape = []; + $this->records = []; + + return [ + 'type' => $this->signature($type, $name), + 'records' => array_values($this->records), + ]; + } + + /** @return array */ + private function signature(Type $type, string $name): array + { + return match ($type->kind) { + TypeKind::Optional => [ + 'kind' => 'optional', + 'value' => $this->signature($this->itemType($type), $name), + ], + TypeKind::Array => [ + 'kind' => 'array', + 'value' => ['item' => $this->signature($this->itemType($type), Str::singular($name))], + ], + TypeKind::Struct, TypeKind::Enum => [ + 'kind' => 'record', + 'value' => $this->recordId($type, $name), + ], + default => [ + 'kind' => 'primitive', + 'value' => $type->kind->value, + ], + }; + } + + private function recordId(Type $type, string $name): string + { + $shape = serialize($type); + + if (isset($this->recordIdsByShape[$shape])) { + return $this->recordIdsByShape[$shape]; + } + + $recordId = $this->uniqueRecordId($name); + + // Registered before its fields are described, so the definitions come out parent first. + $this->recordIdsByShape[$shape] = $recordId; + $this->records[$recordId] = []; + $this->records[$recordId] = $type->kind === TypeKind::Struct + ? $this->structDefinition($type, $recordId) + : $this->enumDefinition($type, $recordId); + + return $recordId; + } + + private function uniqueRecordId(string $name): string + { + $studlyName = Str::studly($name); + $recordId = self::MODULE.":{$studlyName}"; + $suffix = 2; + + while (isset($this->records[$recordId])) { + $recordId = self::MODULE.":{$studlyName}{$suffix}"; + $suffix++; + } + + return $recordId; + } + + /** @return array */ + private function structDefinition(Type $type, string $recordId): array + { + $fields = []; + $removedNumbers = []; + + foreach ($type->fields as $field) { + if ($field->removed) { + $removedNumbers[] = $field->number; + + continue; + } + + $fields[] = $this->fieldDefinition($field); + } + + $definition = [ + 'kind' => 'struct', + 'id' => $recordId, + 'fields' => $fields, + ]; + + if ($removedNumbers !== []) { + $definition['removed_numbers'] = $removedNumbers; + } + + return $definition; + } + + /** @return array */ + private function fieldDefinition(Field $field): array + { + $name = (string) $field->name; + + return [ + 'name' => $name, + 'number' => $field->number, + 'type' => $this->signature($field->type ?? Type::bool(), $name), + ]; + } + + /** @return array */ + private function enumDefinition(Type $type, string $recordId): array + { + $variants = []; + + foreach ($type->variants as $variant) { + // Number 0 is the implicit UNKNOWN variant, which type descriptors leave out. + if ($variant->number === 0) { + continue; + } + + $variants[] = $this->variantDefinition($variant); + } + + return [ + 'kind' => 'enum', + 'id' => $recordId, + 'variants' => $variants, + ]; + } + + /** @return array */ + private function variantDefinition(Variant $variant): array + { + $definition = [ + 'name' => $variant->name, + 'number' => $variant->number, + ]; + + if ($variant->payloadType !== null) { + $definition['type'] = $this->signature($variant->payloadType, $variant->name); + } + + return $definition; + } + + private function itemType(Type $type): Type + { + return $type->itemType ?? Type::bool(); + } +} diff --git a/tests/Feature/LaravelControllerDispatchTest.php b/tests/Feature/LaravelControllerDispatchTest.php index b62bb49..6c2ee9e 100644 --- a/tests/Feature/LaravelControllerDispatchTest.php +++ b/tests/Feature/LaravelControllerDispatchTest.php @@ -547,7 +547,7 @@ public function studio_bypasses_procedure_middleware_while_calls_remain_protecte $this->registerController('/protected-studio', MethodMiddlewareController::class)->studio(); $this - ->get('/protected-studio?studio') + ->get('/protected-studio?list') ->assertOk() ->assertSee('GetMe'); diff --git a/tests/Feature/SkirRpcControllerTest.php b/tests/Feature/SkirRpcControllerTest.php index 9f4f3f9..c18f066 100644 --- a/tests/Feature/SkirRpcControllerTest.php +++ b/tests/Feature/SkirRpcControllerTest.php @@ -237,10 +237,12 @@ public function it_exposes_endpoint_studio_when_enabled_on_the_route(): void ->get('/studio-rpc?studio') ->assertOk() ->assertHeader('content-type', 'text/html; charset=UTF-8') - ->assertSee('Skir RPC Studio') - ->assertSee('Square') - ->assertSee('Double') - ->assertSee('/studio-rpc'); + ->assertSee('skir-studio-app'); + + $this + ->get('/studio-rpc?list') + ->assertOk() + ->assertJsonPath('methods.*.method', ['Square', 'Double']); } #[Test] @@ -372,7 +374,7 @@ public function studio_lists_controller_registered_methods(): void ])->studio(); $this - ->get('/controller-studio-rpc?studio') + ->get('/controller-studio-rpc?list') ->assertOk() ->assertSee('Double') ->assertSee('RenameUser') diff --git a/tests/Feature/SkirServerConfigurationTest.php b/tests/Feature/SkirServerConfigurationTest.php index 52f8f36..8846353 100644 --- a/tests/Feature/SkirServerConfigurationTest.php +++ b/tests/Feature/SkirServerConfigurationTest.php @@ -41,7 +41,7 @@ public function studio_can_be_enabled_by_configuration(): void ->get('/configured-studio?studio') ->assertOk() ->assertHeader('content-type', 'text/html; charset=UTF-8') - ->assertSee('Skir RPC Studio'); + ->assertSee('skir-studio-app'); } #[Test] @@ -73,13 +73,13 @@ public function studio_query_key_can_be_configured(): void $this ->get('/configured-studio-query-key?studio') ->assertUnprocessable() - ->assertDontSee('Skir RPC Studio'); + ->assertDontSee('skir-studio-app'); $this ->get('/configured-studio-query-key?skir-studio') ->assertOk() ->assertHeader('content-type', 'text/html; charset=UTF-8') - ->assertSee('Skir RPC Studio'); + ->assertSee('skir-studio-app'); } #[Test] @@ -103,12 +103,12 @@ public function studio_configuration_is_snapshotted_when_the_route_is_registered ->get('/snapshotted-studio?registered-studio') ->assertOk() ->assertHeader('content-type', 'text/html; charset=UTF-8') - ->assertSee('Skir RPC Studio'); + ->assertSee('skir-studio-app'); $this ->get('/snapshotted-studio?changed-studio') ->assertUnprocessable() - ->assertDontSee('Skir RPC Studio'); + ->assertDontSee('skir-studio-app'); } #[Test] diff --git a/tests/Feature/StudioMethodListTest.php b/tests/Feature/StudioMethodListTest.php new file mode 100644 index 0000000..771cd0f --- /dev/null +++ b/tests/Feature/StudioMethodListTest.php @@ -0,0 +1,174 @@ +studio(); + + $this + ->get('/empty-list?list') + ->assertOk() + ->assertExactJson(['methods' => []]); + } + + #[Test] + public function the_method_list_is_hidden_when_studio_is_disabled(): void + { + Route::skirRpc('/hidden-list')->studio(false); + + $this + ->get('/hidden-list?list') + ->assertNotFound(); + } + + #[Test] + public function it_describes_methods_as_skir_type_descriptors(): void + { + $server = new SkirServer(new ProcedureRegistry); + $server->addMethod($this->inviteDescriptor(), fn (array $request): array => $request); + + $this->assertSame([ + 'methods' => [[ + 'method' => 'Invite', + 'number' => 7001, + 'request' => [ + 'type' => ['kind' => 'record', 'value' => 'skir:InviteRequest'], + 'records' => [ + [ + 'kind' => 'struct', + 'id' => 'skir:InviteRequest', + 'fields' => [ + [ + 'name' => 'email', + 'number' => 0, + 'type' => ['kind' => 'primitive', 'value' => 'string'], + ], + [ + 'name' => 'account_type', + 'number' => 2, + 'type' => ['kind' => 'record', 'value' => 'skir:AccountType'], + ], + [ + 'name' => 'details', + 'number' => 3, + 'type' => [ + 'kind' => 'optional', + 'value' => [ + 'kind' => 'array', + 'value' => ['item' => ['kind' => 'record', 'value' => 'skir:Detail']], + ], + ], + ], + ], + 'removed_numbers' => [1], + ], + [ + 'kind' => 'enum', + 'id' => 'skir:AccountType', + 'variants' => [ + ['name' => 'athlete', 'number' => 1], + [ + 'name' => 'coach', + 'number' => 2, + 'type' => ['kind' => 'primitive', 'value' => 'int32'], + ], + ], + ], + [ + 'kind' => 'struct', + 'id' => 'skir:Detail', + 'fields' => [ + [ + 'name' => 'label', + 'number' => 0, + 'type' => ['kind' => 'primitive', 'value' => 'string'], + ], + ], + ], + ], + ], + 'response' => [ + 'type' => [ + 'kind' => 'optional', + 'value' => ['kind' => 'primitive', 'value' => 'bytes'], + ], + 'records' => [], + ], + ]], + ], (new MethodList)->toArray($server)); + } + + #[Test] + public function records_with_the_same_shape_share_one_definition_and_clashing_names_are_numbered(): void + { + $detail = Type::struct([Field::value('label', 0, Type::string())]); + $otherDetail = Type::struct([Field::value('value', 0, Type::int32())]); + + $server = new SkirServer(new ProcedureRegistry); + $server->addMethod( + new MethodDescriptor( + 'Compare', + 7002, + Type::struct([ + Field::value('detail', 0, $detail), + Field::value('previous', 1, $detail), + Field::value('details', 2, Type::array($otherDetail)), + ]), + Type::bool(), + ), + fn (array $request): bool => true, + ); + + $request = (new MethodList)->toArray($server)['methods'][0]['request']; + + $this->assertSame( + ['skir:CompareRequest', 'skir:Detail', 'skir:Detail2'], + array_column($request['records'], 'id'), + ); + $this->assertSame( + ['skir:Detail', 'skir:Detail', 'skir:Detail2'], + [ + $request['records'][0]['fields'][0]['type']['value'], + $request['records'][0]['fields'][1]['type']['value'], + $request['records'][0]['fields'][2]['type']['value']['item']['value'], + ], + ); + } + + private function inviteDescriptor(): MethodDescriptor + { + return new MethodDescriptor( + 'Invite', + 7001, + Type::struct([ + Field::value('email', 0, Type::string()), + Field::removed(1), + Field::value('account_type', 2, Type::enum([ + Variant::constant('athlete', 1), + Variant::wrapper('coach', 2, Type::int32()), + ])), + Field::value('details', 3, Type::optional(Type::array(Type::struct([ + Field::value('label', 0, Type::string()), + ])))), + ]), + Type::optional(Type::bytes()), + ); + } +} diff --git a/tests/Feature/StudioRendererTest.php b/tests/Feature/StudioRendererTest.php index fa2060b..0e9d3f4 100644 --- a/tests/Feature/StudioRendererTest.php +++ b/tests/Feature/StudioRendererTest.php @@ -6,153 +6,54 @@ use Illuminate\Support\Facades\Route; use PHPUnit\Framework\Attributes\Test; -use Skir\Runtime\Field; -use Skir\Runtime\MethodDescriptor; -use Skir\Runtime\Type; -use Skir\Runtime\Variant; -use Skir\Server\ProcedureRegistry; -use Skir\Server\SkirServer; use Skir\Server\Studio\StudioRenderer; use Skir\Server\Tests\TestCase; final class StudioRendererTest extends TestCase { #[Test] - public function it_renders_an_empty_state_when_no_procedures_are_registered(): void + public function it_serves_the_official_studio_app(): void { - Route::skirRpc('/empty-studio')->studio(); + Route::skirRpc('/studio')->studio(); $this - ->get('/empty-studio?studio') + ->get('/studio?studio') ->assertOk() - ->assertSee('No Skir procedures are registered for this endpoint.'); + ->assertHeader('content-type', 'text/html; charset=UTF-8') + ->assertSee('', escape: false) + ->assertSee('', escape: false); } #[Test] - public function head_requests_can_open_studio_with_a_suppressed_body(): void + public function the_studio_app_script_is_configurable(): void { - Route::skirRpc('/head-studio')->studio(); + config(['skir-server.studio_app_js_url' => 'https://assets.example.test/studio.js']); + Route::skirRpc('/self-hosted-studio')->studio(); $this - ->call('HEAD', '/head-studio?studio') + ->get('/self-hosted-studio?studio') ->assertOk() - ->assertHeader('content-type', 'text/html; charset=UTF-8') - ->assertContent(''); + ->assertSee('', escape: false); } #[Test] - public function it_serializes_nested_type_metadata(): void + public function head_requests_can_open_studio_with_a_suppressed_body(): void { - $server = new SkirServer(new ProcedureRegistry); - $server->addMethod($this->complexDescriptor(), fn (array $request): array => $request); - - $metadata = $this->metadataFromHtml(app(StudioRenderer::class)->render($server, '/skir')); + Route::skirRpc('/head-studio')->studio(); - $this->assertSame([ - 'endpoint' => '/skir', - 'methods' => [[ - 'name' => 'ComplexMethod', - 'number' => 7001, - 'request' => [ - 'kind' => 'struct', - 'fields' => [ - [ - 'name' => 'items', - 'number' => 0, - 'removed' => false, - 'type' => [ - 'kind' => 'array', - 'item' => ['kind' => 'string'], - ], - ], - [ - 'name' => null, - 'number' => 1, - 'removed' => true, - ], - [ - 'name' => 'choice', - 'number' => 2, - 'removed' => false, - 'type' => [ - 'kind' => 'enum', - 'variants' => [ - [ - 'name' => 'None', - 'number' => 0, - ], - [ - 'name' => 'Value', - 'number' => 1, - 'payload' => ['kind' => 'int32'], - ], - ], - ], - ], - ], - ], - 'response' => [ - 'kind' => 'optional', - 'item' => ['kind' => 'bytes'], - ], - ]], - ], $metadata); + $this + ->call('HEAD', '/head-studio?studio') + ->assertOk() + ->assertHeader('content-type', 'text/html; charset=UTF-8') + ->assertContent(''); } #[Test] - public function it_escapes_endpoint_and_method_names(): void - { - $server = new SkirServer(new ProcedureRegistry); - $server->addMethod( - new MethodDescriptor('', 7002, Type::string(), Type::string()), - fn (string $request): string => $request, - ); - - $html = app(StudioRenderer::class)->render($server, '/'); - $metadata = $this->metadataFromHtml($html); - - $this->assertStringNotContainsString('', $html); - $this->assertStringNotContainsString('/', $html); - $this->assertStringContainsString('<script>method</script>', $html); - $this->assertStringContainsString('/<script>endpoint</script>', $html); - $this->assertSame('', $metadata['methods'][0]['name']); - $this->assertSame('/', $metadata['endpoint']); - } - - private function complexDescriptor(): MethodDescriptor + public function it_escapes_the_app_script_url(): void { - return new MethodDescriptor( - 'ComplexMethod', - 7001, - Type::struct([ - Field::value('items', 0, Type::array(Type::string())), - Field::removed(1), - Field::value('choice', 2, Type::enum([ - Variant::constant('None', 0), - Variant::wrapper('Value', 1, Type::int32()), - ])), - ]), - Type::optional(Type::bytes()), - ); - } - - /** - * @return array{ - * endpoint: string, - * methods: array> - * } - */ - private function metadataFromHtml(string $html): array - { - $matched = preg_match('/data-skir-studio="([^"]*)"/', $html, $matches); - - $this->assertSame(1, $matched); - - $json = html_entity_decode($matches[1], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); - $metadata = json_decode($json, true, flags: JSON_THROW_ON_ERROR); - - $this->assertIsArray($metadata); + $html = app(StudioRenderer::class)->render('https://example.test/studio.js">'); - return $metadata; + $this->assertStringNotContainsString('', $html); + $this->assertStringContainsString('"></script>', $html); } }