kernelconnector.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (c) Jupyter Development Team.
  2. // Distributed under the terms of the Modified BSD License.
  3. import {
  4. IClientSession
  5. } from '@jupyterlab/apputils';
  6. import {
  7. DataConnector
  8. } from '@jupyterlab/coreutils';
  9. import {
  10. KernelMessage
  11. } from '@jupyterlab/services';
  12. import {
  13. InspectionHandler
  14. } from './handler';
  15. /**
  16. * The default connector for making inspection requests from the Jupyter API.
  17. */
  18. export
  19. class KernelConnector extends DataConnector<InspectionHandler.IReply, void, InspectionHandler.IRequest> {
  20. /**
  21. * Create a new kernel connector for inspection requests.
  22. *
  23. * @param options - The instatiation options for the kernel connector.
  24. */
  25. constructor(options: KernelConnector.IOptions) {
  26. super();
  27. this._session = options.session;
  28. }
  29. /**
  30. * Fetch inspection requests.
  31. *
  32. * @param request - The inspection request text and details.
  33. */
  34. fetch(request: InspectionHandler.IRequest): Promise<InspectionHandler.IReply> {
  35. const kernel = this._session.kernel;
  36. if (!kernel) {
  37. return Promise.reject(new Error('Inspection fetch requires a kernel.'));
  38. }
  39. const contents: KernelMessage.IInspectRequest = {
  40. code: request.text,
  41. cursor_pos: request.offset,
  42. detail_level: 0
  43. };
  44. return kernel.requestInspect(contents).then(msg => {
  45. const response = msg.content;
  46. if (response.status !== 'ok' || !response.found) {
  47. throw new Error('Inspection fetch failed to return successfully.');
  48. }
  49. return { data: response.data, metadata: response.metadata };
  50. });
  51. }
  52. private _session: IClientSession;
  53. }
  54. /**
  55. * A namespace for kernel connector statics.
  56. */
  57. export
  58. namespace KernelConnector {
  59. /**
  60. * The instantiation options for an inspection handler.
  61. */
  62. export
  63. interface IOptions {
  64. /**
  65. * The session used to make API requests to the kernel.
  66. */
  67. session: IClientSession;
  68. }
  69. }