Skip to content

Commit

Permalink
fix: import protobufjs/minimal with importSuffix (#616)
Browse files Browse the repository at this point in the history
Add a new impFile function which uses the importSuffix to import.

Use impFile for protobufjs/minimal such that;

If importSuffix='.js' then:

import * as _m1 from 'protobufjs/minimal.js';

Fixes esmodule interop.

Adjust ts-poet options to fix importing the default module from
protobufjs/minimal.js if necessary.
  • Loading branch information
DevSlashRichie authored Jul 16, 2022
1 parent 6c78d7e commit b86291c
Show file tree
Hide file tree
Showing 11 changed files with 37 additions and 22 deletions.
2 changes: 1 addition & 1 deletion integration/codegen.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { CodeGeneratorRequest, FileDescriptorProto } from 'ts-proto-descriptors';
import { CodeGeneratorRequest } from 'ts-proto-descriptors';
import { mkdir, readFile, writeFile } from 'fs';
import { parse } from 'path';
import { promisify } from 'util';
Expand Down
2 changes: 1 addition & 1 deletion integration/import-suffix/child.pb.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable */
import * as _m0 from 'protobufjs/minimal';
import * as _m0 from 'protobufjs/minimal.js';

export const protobufPackage = 'file_suffix';

Expand Down
2 changes: 1 addition & 1 deletion integration/import-suffix/google/protobuf/timestamp.pb.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable */
import * as Long from 'long';
import * as _m0 from 'protobufjs/minimal';
import * as _m0 from 'protobufjs/minimal.js';

export const protobufPackage = 'google.protobuf';

Expand Down
2 changes: 1 addition & 1 deletion integration/import-suffix/parent.pb.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable */
import { ChildEnum, Child, childEnumFromJSON, childEnumToJSON } from './child.pb.js';
import { Timestamp } from './google/protobuf/timestamp.pb.js';
import * as _m0 from 'protobufjs/minimal';
import * as _m0 from 'protobufjs/minimal.js';

export const protobufPackage = 'file_suffix';

Expand Down
2 changes: 1 addition & 1 deletion integration/simple-esmodule-interop/simple.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/* eslint-disable */
import Long from 'long';
import * as _m0 from 'protobufjs/minimal';
import _m0 from 'protobufjs/minimal';

export const protobufPackage = 'simple';

Expand Down
13 changes: 10 additions & 3 deletions src/generate-services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,20 @@ import {
responseType,
observableType,
} from './types';
import { assertInstanceOf, FormattedMethodDescriptor, maybeAddComment, maybePrefixPackage, singular } from './utils';
import {
assertInstanceOf,
FormattedMethodDescriptor,
impFile,
maybeAddComment,
maybePrefixPackage,
singular,
} from './utils';
import SourceInfo, { Fields } from './sourceInfo';
import { contextTypeVar } from './main';
import { Context } from './context';

const hash = imp('hash*object-hash');
const dataloader = imp('DataLoader*dataloader');
const Reader = imp('Reader@protobufjs/minimal');

/**
* Generates an interface for `serviceDesc`.
Expand Down Expand Up @@ -105,7 +111,7 @@ function generateRegularRpcMethod(
): Code {
assertInstanceOf(methodDesc, FormattedMethodDescriptor);
const { options, utils } = ctx;
const Reader = imp('Reader@protobufjs/minimal');
const Reader = impFile(ctx.options, 'Reader@protobufjs/minimal');
const rawInputType = rawRequestType(ctx, methodDesc);
const inputType = requestType(ctx, methodDesc);
const outputType = responseType(ctx, methodDesc);
Expand Down Expand Up @@ -276,6 +282,7 @@ function generateCachingRpcMethod(
const inputType = requestType(ctx, methodDesc);
const outputType = responseType(ctx, methodDesc);
const uniqueIdentifier = `${maybePrefixPackage(fileDesc, serviceDesc.name)}.${methodDesc.name}`;
const Reader = impFile(ctx.options, 'Reader@protobufjs/minimal');
const lambda = code`
(requests) => {
const responses = requests.map(async request => {
Expand Down
9 changes: 5 additions & 4 deletions src/generate-type-registry.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import { code, Code, imp, joinCode } from 'ts-poet';
import { code, Code, joinCode } from 'ts-poet';
import { Context } from './context';

const Writer = imp('Writer@protobufjs/minimal');
const Reader = imp('Reader@protobufjs/minimal');
import { impFile } from './utils';

export function generateTypeRegistry(ctx: Context): Code {
const chunks: Code[] = [];
Expand Down Expand Up @@ -30,6 +28,9 @@ function generateMessageType(ctx: Context): Code {
chunks.push(code`$type: Message['$type'];`);

if (ctx.options.outputEncodeMethods) {
const Writer = impFile(ctx.options, 'Writer@protobufjs/minimal');
const Reader = impFile(ctx.options, 'Reader@protobufjs/minimal');

chunks.push(code`encode(message: Message, writer?: ${Writer}): ${Writer};`);
chunks.push(code`decode(input: ${Reader} | Uint8Array, length?: number): Message;`);
}
Expand Down
14 changes: 8 additions & 6 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import {
maybeAddComment,
maybePrefixPackage,
getPropertyAccessor,
impFile,
} from './utils';
import { camelToSnake, capitalize, maybeSnakeToCamel } from './case';
import {
Expand Down Expand Up @@ -196,7 +197,7 @@ export function generateFile(ctx: Context, fileDesc: FileDescriptorProto): [stri
`);

if (options.outputTypeRegistry) {
const messageTypeRegistry = imp('messageTypeRegistry@./typeRegistry');
const messageTypeRegistry = impFile(options, 'messageTypeRegistry@./typeRegistry');

chunks.push(code`
${messageTypeRegistry}.set(${fullName}.$type, ${fullName});
Expand Down Expand Up @@ -335,8 +336,8 @@ export function makeUtils(options: Options): Utils {
function makeLongUtils(options: Options, bytes: ReturnType<typeof makeByteUtils>) {
// Regardless of which `forceLong` config option we're using, we always use
// the `long` library to either represent or at least sanity-check 64-bit values
const util = imp('util@protobufjs/minimal');
const configure = imp('configure@protobufjs/minimal');
const util = impFile(options, 'util@protobufjs/minimal');
const configure = impFile(options, 'configure@protobufjs/minimal');

// Before esModuleInterop, we had to use 'import * as Long from long` b/c long is
// an `export =` module and exports only the Long constructor (which is callable).
Expand Down Expand Up @@ -808,6 +809,8 @@ function generateDecode(ctx: Context, fullName: string, messageDesc: DescriptorP
createBase = code`Object.create(${createBase}) as ${fullName}`;
}

const Reader = impFile(ctx.options, 'Reader@protobufjs/minimal');

// create the basic function declaration
chunks.push(code`
decode(
Expand Down Expand Up @@ -943,14 +946,13 @@ function generateDecode(ctx: Context, fullName: string, messageDesc: DescriptorP
return joinCode(chunks, { on: '\n' });
}

const Writer = imp('Writer@protobufjs/minimal');
const Reader = imp('Reader@protobufjs/minimal');

/** Creates a function to encode a message by loop overing the tags. */
function generateEncode(ctx: Context, fullName: string, messageDesc: DescriptorProto): Code {
const { options, utils, typeMap } = ctx;
const chunks: Code[] = [];

const Writer = impFile(ctx.options, 'Writer@protobufjs/minimal');

// create the basic function declaration
chunks.push(code`
encode(
Expand Down
5 changes: 3 additions & 2 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ function parseParameter(parameter: string): Options {
return options;
}

export function getTsPoetOpts(_options: Options): { forceModuleImport?: string[] } {
return { forceModuleImport: ['protobufjs/minimal'] };
export function getTsPoetOpts(_options: Options): { forceModuleImport?: string[]; forceDefaultImport?: string[] } {
const imports = ['protobufjs/minimal' + _options.importSuffix];
return _options.esModuleInterop ? { forceDefaultImport: imports } : { forceModuleImport: imports };
}
4 changes: 2 additions & 2 deletions src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { imp, code, Code, joinCode, def } from 'ts-poet';
import { visit, visitServices } from './visit';
import { Context } from './context';
import SourceInfo from './sourceInfo';
import { maybePrefixPackage } from './utils';
import { impFile, maybePrefixPackage } from './utils';
import { basicTypeName, toReaderCall } from './types';
import { Reader } from 'protobufjs/minimal';

Expand Down Expand Up @@ -87,7 +87,7 @@ export function generateSchema(ctx: Context, fileDesc: FileDescriptorProto, sour
});

const dependencies = fileDesc.dependency.map((dep) => {
return code`${imp(`protoMetadata@./${dep.replace('.proto', '')}`)}`;
return code`${impFile(options, `protoMetadata@./${dep.replace('.proto', '')}`)}`;
});

// Use toObject so that we get enums as numbers (instead of the default toJSON behavior)
Expand Down
4 changes: 4 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,10 @@ export function getPropertyAccessor(objectName: string, propertyName: string, op
: `${objectName}${optional ? '?.' : ''}[${JSON.stringify(propertyName)}]`;
}

export function impFile(options: Options, spec: string) {
return imp(`${spec}${options.importSuffix}`);
}

export function impProto(options: Options, module: string, type: string): Import {
const importString = `${type}@./${module}${options.fileSuffix}${options.importSuffix}`;
if (options.onlyTypes) {
Expand Down

0 comments on commit b86291c

Please sign in to comment.