Telescope
Developing
Common helpers or utils

Common helpers or utils

when generating code, sometimes we need to import helpers, utils or packages. In that case, using addUtil method in context when building ast is recommend, since we only add utils as needed without worrying repetitive import:

context.addUtil('useQuery');

We need to edit several files to make this work under packages/telescope:

├── telescope
    ├── src
        ├── generators
            ├── create-helpers.ts
        ├── helpers
            ├── ...all helpers.ts
            ├── index.ts
        ├── utils
            ├── index.ts
folderpurpose
all helpers.tsfiles that contain common code, will be used in create-helper.ts
helpers/index.tsexport files defined in this folder.
create-helpers.tscreate helper files as needed using contents defined in helper folder.
utils/index.tsthis defines mappings of common functions and packages. And defines alias for common helper files.

0 mapping functions with packages

add mapping between function and package in packages/telescope/src/utils/index.ts. In this example, two ways of mappings are shown:

export const UTILS = {
  // this will create import * as _m0 from "protobufjs/minimal";
  _m0: { type: 'namespace', path: 'protobufjs/minimal', name: '_m0' },
  ... other mappings
  // this will create import useQuery from '@tanstack/react-query'
  useQuery: '@tanstack/react-query',
};

If we have to import from the helper files created by ourselves, we can continue reading sections below.

1 create helper contents

In this example, content of a common helper will be created and exported under folder apackages/telescope/src/helpers

export const useEndpoint = defineStore('endpoint', {
 
})
`;

And export this file in packages/telescope/src/helpers/index.ts.

export * from './endpoint';

2 generate helper file

In this example, the endpoint helper will be generated by packages/telescope/src/generators/create-helpers.ts

import { endpoints } from '../helpers';
export const plugin = (
  builder: TelescopeBuilder
) => {
  write(builder, 'helpers.ts', internal);
 
  // generate based on option
  if (builder.options.isEndpointsIncluded) {
    builder.files.push('endpoints.ts');
    write(builder, 'endpoints.ts', endpoints);
  }
 
};

3 set alias for the helper file and mapping

we have to set an alias for generated helper file in packages/telescope/src/utils/index.ts. The rule is taking the filename part without extension and then surrounding with "__". For example: for the file "endpoints.ts", the alias would be "__endpoints__". In this example, an alias is created and a mapping is built.

export const UTILS = {
  ... other mappings
  useEndpoint: "__endpoints__"
};

export const UTIL_HELPERS = [
  ... other aliases
  // this will be automatically resolved to correct path in the final result.
  '__endpoints__'
];