change-case#camelCase TypeScript Examples

The following examples show how to use change-case#camelCase. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From graphql-mesh with MIT License 7 votes vote down vote up
export function getFieldNameFromPath(path: string, method: string, typeName: string) {
  // Replace identifiers with "by"
  path = path.split('{').join('by_').split('}').join('');

  const [actualPartsStr, allQueryPartsStr] = path.split('?');

  const actualParts = actualPartsStr.split('/').filter(Boolean);

  let fieldNameWithoutMethod = actualParts.join('_');

  // If path doesn't give any field name without identifiers, we can use the return type with HTTP Method name
  if ((!fieldNameWithoutMethod || fieldNameWithoutMethod.startsWith('by')) && typeName) {
    // lowercase looks better in the schema
    const prefix = camelCase(typeName);
    if (fieldNameWithoutMethod) {
      fieldNameWithoutMethod = prefix + '_' + fieldNameWithoutMethod;
    } else {
      fieldNameWithoutMethod = prefix;
    }
  }

  if (allQueryPartsStr) {
    const queryParts = allQueryPartsStr.split('&');
    for (const queryPart of queryParts) {
      const [queryName] = queryPart.split('=');
      fieldNameWithoutMethod += '_' + 'by' + '_' + queryName;
    }
  }

  // get_ doesn't look good in field names
  const methodPrefix = method.toLowerCase();
  if (methodPrefix === 'get') {
    return fieldNameWithoutMethod;
  }
  return methodPrefix + '_' + fieldNameWithoutMethod;
}
Example #2
Source File: utils.ts    From jsonapi-fractal with MIT License 7 votes vote down vote up
/**
 * Used to change the case (e.g. captalization) of the keys of a object
 *
 * @param originalAttributes
 * @param caseType
 * @param deep
 */
export function changeCase(originalAttributes: AttributesObject, caseType: CaseType, deep = false): AttributesObject {
  const caseTypes: Record<CaseType, CaseFunction> = {
    [CaseType.camelCase]: camelCase,
    [CaseType.snakeCase]: snakeCase,
    [CaseType.kebabCase]: paramCase,
  }

  const caseFunction = caseTypes[caseType]

  if (!caseFunction) {
    throw new Error('Invalid case type: ' + caseType)
  }

  const parsedAttributes: AttributesObject = {}

  for (const key of Object.keys(originalAttributes)) {
    let value = originalAttributes[key]

    if (deep && value) {
      if (Array.isArray(value)) {
        value = value.map((value) => (isObject(value) ? changeCase(value as JsonObject, caseType, deep) : value))
      } else if (isObject(value)) {
        value = changeCase(value as JsonObject, caseType, deep)
      }
    }

    parsedAttributes[caseFunction(key)] = value
  }

  return parsedAttributes
}
Example #3
Source File: utils.ts    From graphql-mesh with MIT License 6 votes vote down vote up
export function getFieldNameFromPath(path: string, method: string, responseTypeSchemaRef: string) {
  // Replace identifiers with "by"
  path = path.split('{').join('by_').split('}').join('');

  const [actualPartsStr, allQueryPartsStr] = path.split('?');

  const actualParts = actualPartsStr.split('/').filter(Boolean);

  let fieldNameWithoutMethod = actualParts.join('_');

  // If path doesn't give any field name without identifiers, we can use the return type with HTTP Method name
  if ((!fieldNameWithoutMethod || fieldNameWithoutMethod.startsWith('by')) && responseTypeSchemaRef) {
    const refArr = responseTypeSchemaRef.split('/');
    // lowercase looks better in the schema
    const prefix = camelCase(refArr[refArr.length - 1]);
    if (fieldNameWithoutMethod) {
      fieldNameWithoutMethod = prefix + '_' + fieldNameWithoutMethod;
    } else {
      fieldNameWithoutMethod = prefix;
    }
  }

  if (allQueryPartsStr) {
    const queryParts = allQueryPartsStr.split('&');
    for (const queryPart of queryParts) {
      const [queryName] = queryPart.split('=');
      fieldNameWithoutMethod += '_' + 'by' + '_' + queryName;
    }
  }

  // get_ doesn't look good in field names
  const methodPrefix = method.toLowerCase();
  if (methodPrefix === 'get') {
    return fieldNameWithoutMethod;
  }
  if (fieldNameWithoutMethod) {
    return methodPrefix + '_' + fieldNameWithoutMethod;
  }
  return methodPrefix;
}
Example #4
Source File: apiCamelCase.ts    From taiga-front-next with GNU Affero General Public License v3.0 6 votes vote down vote up
apiCamelCaseReplacements = (rootNode: SourceFile) => {
  rootNode.forEachDescendant((node) => {
    if (
      node.getKind() === ts.SyntaxKind.StringLiteral &&
      node.getParent()?.getKind() !== ts.SyntaxKind.ImportDeclaration &&
      valid(node.getText())) {
      const text = node.getText();
      node.replaceWithText(text[0] === '\'' ? `'${camelCase(text)}'` : camelCase(text));
    } else if (node.getKind() === ts.SyntaxKind.Identifier &&
        valid(node.getText()) &&
        (node.getParent()?.getKind() === ts.SyntaxKind.PropertySignature ||
        node.getParent()?.getKind() === ts.SyntaxKind.PropertyAssignment ||
        node.getParent()?.getKind() === ts.SyntaxKind.PropertyAccessExpression)) {
        const text = node.getText();
        node.replaceWithText(camelCase(text));
    }
  });
}
Example #5
Source File: getRefinedFilename.ts    From ctix with MIT License 6 votes vote down vote up
export default function getRefinedFilename(filename: string): string {
  const basename = path.basename(filename, path.extname(filename));

  if (/^([A-Z])(.+)/.test(basename)) {
    return upperCaseFirst(camelCase(basename));
  }

  return camelCase(basename);
}
Example #6
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
propertyFromInputField(field: GraphQLInputField) {
    return Object.assign(
      {},
      {
        propertyName: camelCase(field.name),
        typeName: this.typeNameFromGraphQLType(field.type),
        isOptional: !(field.type instanceof GraphQLNonNull),
        description: field.description || null,
        name: field.name,
      }
    );
  }
Example #7
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
propertyFromFragmentSpread(fragmentSpread: FragmentSpread, isConditional: boolean): FragmentSpread & Property & Struct {
    const structName = this.structNameForFragmentName(fragmentSpread.fragmentName);

    return Object.assign({}, fragmentSpread, {
      propertyName: camelCase(fragmentSpread.fragmentName),
      typeName: isConditional ? structName + '?' : structName,
      structName,
      isConditional,
    });
  }
Example #8
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
propertyFromVariant(variant: Variant): Variant & Property & Struct {
    const structName = this.structNameForVariant(variant);

    return Object.assign(variant, {
      propertyName: camelCase(structName),
      typeName: structName + '?',
      structName,
    });
  }
Example #9
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
// Properties

  propertyFromField(field: Field, namespace?: string): Field & Property & Struct {
    const { responseKey, isConditional } = field;

    const propertyName = isMetaFieldName(responseKey) ? responseKey : camelCase(responseKey);

    const structName = join([namespace, this.structNameForPropertyName(responseKey)], '.');

    let type = field.type;

    if (isConditional && isNonNullType(type)) {
      type = type.ofType;
    }

    const isOptional = !(type instanceof GraphQLNonNull);

    const unmodifiedType = getNamedType(field.type);

    const unmodifiedTypeName = isCompositeType(unmodifiedType) ? structName : unmodifiedType.name;

    const typeName = this.typeNameFromGraphQLType(type, unmodifiedTypeName);

    return Object.assign({}, field, {
      responseKey,
      propertyName,
      typeName,
      structName,
      isOptional,
    });
  }
Example #10
Source File: validate-field-name.ts    From amplify-codegen with Apache License 2.0 6 votes vote down vote up
/**
 * Validate if two field names have identical camelCase output. This will cause compile error in Java modelgen output.
 * e.g 'due_date' and 'dueDate' will result in the same 'dueDate'
 */
export function validateFieldName(models: CodeGenModelMap) : void {
  Object.entries(models).forEach(([modelName, model]) => {
    let validateMap: any = {};
    model.fields.forEach(field => {
      const key = camelCase(field.name)
      if (key in validateMap) {
        throw new Error(`Fields "${field.name}" and "${validateMap[key]}" in ${model.name} cannot be used at the same time which will result in the duplicate builder method.`);
      }
      validateMap[key] = field.name;
    });
  });
}
Example #11
Source File: index.ts    From graphql-mesh with MIT License 6 votes vote down vote up
NAMING_CONVENTIONS: Record<NamingConventionType, NamingConventionFn> = {
  camelCase,
  capitalCase,
  constantCase,
  dotCase,
  headerCase,
  noCase,
  paramCase,
  pascalCase,
  pathCase,
  sentenceCase,
  snakeCase,
  upperCase,
  lowerCase,
}
Example #12
Source File: BotManager.ts    From tf2autobot with MIT License 5 votes vote down vote up
start(options: Options): Promise<void> {
        return new Promise((resolve, reject) => {
            REQUIRED_OPTS.forEach(optName => {
                if (!process.env[optName] && !options[camelCase(optName)]) {
                    return reject(new Error(`Missing required environment variable "${optName}"`));
                }
            });

            async.eachSeries(
                [
                    (callback): void => {
                        log.debug('Connecting to PM2...');
                        void this.connectToPM2().asCallback(callback);
                    },
                    (callback): void => {
                        log.info('Starting bot...');
                        this.pricer.init(options.enableSocket);
                        this.bot = new Bot(this, options, this.pricer);

                        void this.bot.start().asCallback(callback);
                    }
                ],
                (item, callback) => {
                    if (this.isStopping) {
                        // Shutdown is requested, stop the bot
                        return this.stop(null, false, false);
                    }

                    item(callback);
                },
                err => {
                    if (err) {
                        return reject(err);
                    }

                    if (this.isStopping) {
                        // Shutdown is requested, stop the bot
                        return this.stop(null, false, false);
                    }

                    this.pricer.connect(this.bot?.options.enableSocket);

                    this.schemaManager = this.bot.schemaManager;

                    return resolve();
                }
            );
        });
    }
Example #13
Source File: appsync-java-visitor.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
/**
   * generates Step function argument
   * @param field
   */
  protected getStepFunctionArgumentName(field: CodeGenField): string {
    return camelCase(field.name);
  }
Example #14
Source File: legacy.component.ts    From taiga-front-next with GNU Affero General Public License v3.0 5 votes vote down vote up
public ngOnInit() {
    const channel = new BehaviorSubject<{
      type: string;
      value: any;
    }>({type: 'INIT', value: null});

    channel.subscribe((event) => {
      if (event.type === 'SET_DETAIL_OBJ') {
        this.legacyService.setState({
          detailObj: UtilsService.objKeysTransformer(event.value, camelCase) as any,
        });
      }
    });

    // share service with taiga-old
    const injector = Injector.create({
      providers: [
        {provide: DataConversionService, deps: []},
      ],
    });

    (window as any).legacyChannel = channel;
    (window as any).angularDataConversion = () => {
      return injector.get(DataConversionService);
    };

    this.router.events.pipe(
      filter((e: Event) => {
        return e instanceof NavigationEnd;
      })
    ).subscribe((e: NavigationEnd) => {
      const $location = this.legacyService.getInjector().get('$location');
      const $rootScrope = this.legacyService.getInjector().get('$rootScope');

      if ($location.path() !== e.url) {
        $location.url(e.url);
      }

      $rootScrope.$applyAsync();
    });

    // Tell Angular when the route change in angularjs to keep both framework sync.
    // This fix an issue when the user for example is in /issues,
    // navigate with angular.js to /backlog and the try to go back to /issues
    // with an Angular link, without this code Angular thinks that you already are in /issues
    // so it prevents the navigation.
    this.legacyService.whenAngularReady().then(() => {
      const $location = this.legacyService.getInjector().get('$location');
      const $rootScrope = this.legacyService.getInjector().get('$rootScope');

      $rootScrope.$on('$routeChangeSuccess', () => {
        this.router.navigateByUrl($location.path());

        this.legacyService.setState({
          detailObj: undefined,
        });
      });
    });
  }
Example #15
Source File: camelcase-tranformer.pipe.ts    From taiga-front-next with GNU Affero General Public License v3.0 5 votes vote down vote up
transform(value: object | ArrayLike<unknown>): any {
    return UtilsService.objKeysTransformer(value, camelCase);
  }
Example #16
Source File: api-rest-interceptor.service.ts    From taiga-front-next with GNU Affero General Public License v3.0 5 votes vote down vote up
private camelCaseResponseInterceptor(event: HttpResponse<any>): HttpResponse<any> {
    const body = UtilsService.objKeysTransformer(event.body, camelCase);
    return event.clone({ body });
  }
Example #17
Source File: typescript.ts    From design-systems-cli with MIT License 5 votes vote down vote up
private findStyleUsage(
    css: Map<string, Map<string, Record<string, string>>>
  ) {
    return (
      ctx: ts.TransformationContext
    ): ts.Transformer<ts.SourceFile | ts.Bundle> => (sf) => {
      if (!('fileName' in sf)) {
        return sf;
      }

      const styles = css.get(sf.fileName) || new Map();

      /** Recursively visit all the node in the ts file looking for css usage and imports */
      const visitor: ts.Visitor = (node: ts.Node): ts.Node => {
        if (ts.isPropertyAccessExpression(node)) {
          const variable = node.expression.getText();
          const style = styles.get(variable);

          if (style) {
            const classes = Object.keys(style);
            const camelClasses = classes.map((s) => camelCase(s));
            const className = node.name.getText();
            const exists = Boolean(
              classes.includes(className) || camelClasses.includes(className)
            );

            if (!exists) {
              // We're using internal APIs.... *shh*
              ((ctx as unknown) as WithAddDiagnostic).addDiagnostic({
                category: 1,
                messageText: `ClassName "${className}" does not exists in "${variable}"`,
                start: node.name.getStart(),
                length: className.length,
                file: sf,
                code: 1337,
              });
            }
          }
        }

        return ts.visitEachChild(node, visitor, ctx);
      };

      // Must visit source file instead of the .d.ts file, since that contains no actual code
      const external = ((sf as unknown) as DTsFile).externalModuleIndicator;
      ts.visitNode(external ? external.parent : sf, visitor);

      return sf;
    };
  }
Example #18
Source File: index.ts    From design-systems-cli with MIT License 5 votes vote down vote up
/** Ensure that a user's configuration is valid for the configure CLI */
export function validateConfig(schema: Schema, command: CliCommand): Schema {
  const validationSchema = constructValidationSchema(command);
  const config = flat<Schema, Schema>(schema);

  Object.entries(config).forEach(([configPath, value]) => {
    const parts = configPath.split('.');
    const last = parts[parts.length - 1];
    const isArray = last !== '' && !isNaN(Number(last));

    if (isArray) {
      parts.pop();
    }

    if (configPath.startsWith('plugins.')) {
      if (typeof value !== 'string') {
        throw new Error(
          `Invalid configuration for plugins, all items must be strings`
        );
      }

      return;
    }

    const pathWithSubType = parts
      .map((part) => (isNaN(Number(part)) ? part : 'type'))
      .join('.');

    const type =
      get(validationSchema, pathWithSubType) ||
      get(validationSchema, configPath);

    if (!type) {
      throw new Error(`Invalid configuration option: "${configPath}"`);
    }

    if (type.multiple) {
      if (!isArray) {
        throw new Error(dedent`
          Invalid configuration type ("${typeof value}") for option: "${configPath}"

          Should be: "${type.type}"
        `);
      } else if (isArray && typeof value !== type.type) {
        throw new Error(dedent`
          Invalid configuration type for option array item: "${configPath}" === ${typeof value}

          Should be: "${type.type}"
        `);
      }
    } else if (typeof value !== type.type) {
      throw new Error(dedent`
        Invalid configuration type ("${typeof value}") for option: "${configPath}"

        Should be: "${type.type}"
      `);
    }
  });

  return flat.unflatten(
    fromEntries(
      Object.entries(config).map(([configPath, value]) => [
        configPath
          .split('.')
          .map((part) => camelCase(part))
          .join('.'),
        value,
      ])
    )
  );
}
Example #19
Source File: index.ts    From design-systems-cli with MIT License 5 votes vote down vote up
/** Recursively build the validation schema */
export function getValidationSchema(command: CliCommand) {
  const schema: TypedSchema = {};

  if (command.options) {
    command.options.forEach((option) => {
      if (!option.config) {
        return;
      }

      schema[option.name] = {
        type:
          (option.type === String && 'string') ||
          (option.type === Number && 'number') ||
          'boolean',
      };

      if (option.multiple) {
        schema[option.name].multiple = option.multiple;
      }

      if (option.description) {
        schema[option.name].description = option.description;
      }

      schema[camelCase(option.name)] = schema[option.name];
    });
  }

  if ('commands' in command) {
    command.commands.forEach((subCommand) => {
      const subSchema = getValidationSchema(subCommand);

      if (Object.keys(subSchema).length > 0) {
        schema[subCommand.name] = subSchema;
        schema[camelCase(subCommand.name)] = subSchema;
      }
    });
  }

  return schema;
}
Example #20
Source File: FormatHelpers.ts    From modelina with Apache License 2.0 5 votes vote down vote up
/**
   * Transform into a string with the separator denoted by the next word capitalized.
   * @param {string} value to transform
   * @returns {string}
   */
  static toCamelCase = camelCase;
Example #21
Source File: process-connections.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
export function makeConnectionAttributeName(type: string, field?: string) {
  // The same logic is used graphql-connection-transformer package to generate association field
  // Make sure the logic gets update in that package
  return field ? camelCase([type, field, 'id'].join('_')) : camelCase([type, 'id'].join('_'));
}
Example #22
Source File: appsync-java-visitor.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
/**
   * generates the method name used in step builder
   * @param field
   */
  protected getStepFunctionName(field: CodeGenField): string {
    return camelCase(field.name);
  }
Example #23
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
enumDotCaseName(name: string) {
    return `.${camelCase(name)}`;
  }
Example #24
Source File: helpers.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
// Names

  enumCaseName(name: string) {
    return camelCase(name);
  }
Example #25
Source File: appsync-swift-visitor.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
protected getEnumValue(value: string): string {
    return camelCase(value);
  }
Example #26
Source File: appsync-java-visitor.ts    From amplify-codegen with Apache License 2.0 5 votes vote down vote up
/**
   * Generate code for equals method
   * @param model
   * @param declarationBlock
   */
  protected generateEqualsMethod(model: CodeGenModel, declarationBlock: JavaDeclarationBlock): void {
    const paramName = 'obj';
    const className = this.getModelName(model);
    const instanceName = camelCase(model.name);

    const body = [
      `if (this == ${paramName}) {`,
      '  return true;',
      `} else if(${paramName} == null || getClass() != ${paramName}.getClass()) {`,
      '  return false;',
      '} else {',
    ];

    body.push(`${className} ${instanceName} = (${className}) ${paramName};`);
    const propCheck = indentMultiline(
      this.getNonConnectedField(model)
        .map(field => {
          const getterName = this.getFieldGetterName(field);
          return `ObjectsCompat.equals(${getterName}(), ${instanceName}.${getterName}())`;
        })
        .join(' &&\n'),
      4,
    ).trim();

    body.push(`return ${propCheck};`);
    body.push('}');

    declarationBlock.addClassMethod(
      'equals',
      'boolean',
      indentMultiline(body.join('\n')),
      [{ name: paramName, type: 'Object' }],
      [],
      'public',
      {},
      ['Override'],
    );
  }
Example #27
Source File: run.ts    From design-systems-cli with MIT License 4 votes vote down vote up
/** A plugin to create a completely new system or a new package in a system. */
export default async function run(args: CreateArgs) {
  const command = getCommand(args);

  if (args.listTemplates) {
    logger.info(listTemplates(command, args.template, args.templates));
    return;
  }

  const template = await getTemplatePath(args);
  const skipUnnecessaryPrompts = Boolean(args.name);
  const name = args.name || (await askName(command, args.force));
  const config: TemplateOptions = {
    name,
    authorName:
      (skipUnnecessaryPrompts && defaultAuthorName()) || (await askAuthor()),
    authorEmail:
      (skipUnnecessaryPrompts && defaultAuthorEmail()) || (await askEmail()),
    version: (skipUnnecessaryPrompts && defaultVersion) || (await askVersion()),
    repoUrl:
      ('repo' in args && args.repo) ||
      (skipUnnecessaryPrompts && repo()) ||
      repo() ||
      (await askRepo()),
    monorepoName: monorepoName()
  };
  const pascal = pascalCase(config.name);
  const kebab = paramCase(config.name);
  let destinationDirectory = getDestDirectory(
    command,
    config.name,
    'destination' in args ? args.destination : undefined
  );

  if ('cwd' in args && args.cwd) {
    logger.debug('Creating repo in current working directory...');
    destinationDirectory = '.';
  }

  if ('force' in args && args.force) {
    await fs.remove(destinationDirectory);
  } else if (fs.existsSync(destinationDirectory)) {
    logger.error(
      `Destination directory already exists! '${destinationDirectory}'\n\nRun with --force to ignore`
    );
    process.exit(1);
  }

  logger.debug('Creating templated directory...');
  await copy(template, destinationDirectory, {
    ...config,
    cliVersion,
    title: titleCase(config.name),
    kebab,
    pascal,
    camel: camelCase(config.name)
  });
  logger.debug('Created templated directory!');

  if (command === 'component') {
    logger.success(dedent`\n
      ✨   You made a component  ✨

      ?️   Start developing:

      yarn
      cd ${destinationDirectory}
      yarn dev
    `);
  } else if (command === 'package') {
    logger.success(dedent`\n
      ✨   You made a package  ✨

      ?   Start developing:

      yarn
      cd ${destinationDirectory}
      yarn start
    `);
  } else {
    if ('cwd' in args && !args.cwd) {
      logger.info('Initializing git repo');

      execSync(`cd ${config.name} && git init`);
      execSync(`cd ${config.name} && git remote add origin ${config.repoUrl}`);

      logger.await('Running yarn. This may take a bit...');

      await estimator(
        new Promise<void>((res, rej) => {
          try {
            const isVerbose =
              getLogLevel() === 'debug' || getLogLevel() === 'trace';
            execSync(`cd ${config.name} && yarn`, {
              stdio: isVerbose ? 'inherit' : 'ignore'
            });
            res();
          } catch (error) {
            rej(error);
          }
        }),
        'Installing dependencies',
        72 * 1000 as LogOption
      );
      execSync(
        `cd ${config.name} && git add . && git commit --no-verify -m "Create new design system"`
      );
    }

    logger.success(dedent`\n
      ✨  You made a design system  ✨
        
      ?   Create your first component:
      ${destinationDirectory === '.' ? '' : `\ncd ${destinationDirectory}`}
      yarn run create
    `);
  }
}
Example #28
Source File: WebpackUtils.ts    From design-systems-cli with MIT License 4 votes vote down vote up
config = async ({
  dir,
  name,
  importName,
  analyze,
  analyzerPort,
  chunkByExport,
  diff
}: ConfigOptions & CommonOptions & GetSizesOptions) => {
  const isLocal = name[0] !== '@';
  const js = isLocal ? name : path.join(dir, 'node_modules', name);
  const packageJsonPath = isLocal
    ? path.join(name, 'package.json')
    : path.join(dir, 'node_modules', name, 'package.json');
  const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
  const cssFile = path.join(name, 'dist/main.css');
  const css = isLocal ? cssFile : path.join(dir, 'node_modules', cssFile);
  const peers = Object.keys(packageJson.peerDependencies || {});
  const jsPath = require.resolve(js);
  const { exported } = await getExports.es6(jsPath.replace('cjs', 'esm'));
  const { exported: cjsExports } = await getExports.cjs(jsPath);
  const allExports = exported.length ? exported : cjsExports;
  logger.debug(`Using JS file: ${jsPath}`);
  logger.debug(`Using CSS file: ${css}`);
  logger.debug('Found exported:\n', allExports);
  const plugins: webpack.Plugin[] = [];
  const entry = fromEntries(
    chunkByExport
      ? allExports.map(e => {
          const content = e.default
            ? `export { default as ${camelCase(e.name)} } from "${importName}";`
            : `export { ${e.name} } from "${importName}";`;
          plugins.push(new InjectPlugin(() => content, { entryName: e.name }));
          // This is the actual package "undefined"
          return [e.name, [path.join(__dirname, 'undefined.js')]];
        })
      : [['js', [js]]]
  );
  if (fs.existsSync(css)) {
    entry.css = [css];
  }

  logger.debug('Webpack Entry Files:\n', entry);
  return {
    devtool: false,
    mode: 'production',
    entry,
    output: {
      path: dir
    },
    externals: [
      /^react(-dom)?$/,
      fromEntries(
        Object.keys(packageJson.peerDependencies || {}).map(c => [c, c])
      ),
      /*
       * We need to account for peer dependency sub-paths since webpack does
       * not handle this for us.
       *
       * EX:
       * externals: { "@fuego/gsap-premium": "@fuego/gsap-premium" }
       * will not externalize the following path
       * import "@fuego/gsap-premium/CssPlugin"
       *
       * so this function aims to exclude any sub-path.
       */
      function(context, request, callback) {
        if (peers.find(peer => request.startsWith(`${peer}/`))) {
          logger.debug(`Externalizing: ${request}`);
          return callback(null, JSON.stringify(request));
        }

        callback(undefined, undefined);
      }
    ],
    optimization: {
      minimizer: [new OptimizeCSSAssetsPlugin()]
    },
    module: {
      rules: [
        // https://github.com/apollographql/react-apollo/issues/1737#issuecomment-372946515
        {
          type: 'javascript/auto',
          test: /\.mjs$/,
          use: []
        },
        {
          test: /\.css$/,
          use: [
            {
              loader: MiniCssExtractPlugin.loader
            },
            'css-loader'
          ]
        }
      ]
    },
    plugins: [
      analyze && new BundleAnalyzerPlugin({ analyzerPort }),
      new MiniCssExtractPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify('production')
        }
      }),
      ...plugins,
      diff
        ? new RelativeCommentsPlugin({ importName })
        : new Terser({
            extractComments: false,
            cache: true,
            parallel: true,
            sourceMap: false,
            terserOptions: {
              output: {
                comments: false
              }
            }
          })
    ].filter(Boolean)
  } as webpack.Configuration;
}
Example #29
Source File: appsync-visitor.ts    From amplify-codegen with Apache License 2.0 4 votes vote down vote up
protected generateIntermediateModel(firstModel: CodeGenModel, secondModel: CodeGenModel, relationName: string) {
    const firstModelKeyFieldName = `${camelCase(firstModel.name)}ID`;
    const firstModelSortKeyFields: CodeGenField[] = this.getSortKeyFields(firstModel);
    const secondModelKeyFieldName = `${camelCase(secondModel.name)}ID`;
    const secondModelSortKeyFields: CodeGenField[] = this.getSortKeyFields(secondModel);

    let intermediateModel: CodeGenModel = {
      name: relationName,
      type: 'model',
      directives: [{ name: 'model', arguments: {} }],
      fields: [
        {
          type: 'ID',
          isNullable: false,
          isList: false,
          name: 'id',
          directives: [],
        },
        {
          type: 'ID',
          isNullable: false,
          isList: false,
          name: firstModelKeyFieldName,
          directives: [
            {
              name: 'index',
              arguments: {
                name: 'by' + firstModel.name,
                sortKeyFields: firstModelSortKeyFields.map(f => this.generateIntermediateModelSortKeyFieldName(firstModel, f)),
              },
            },
          ],
        },
        ...firstModelSortKeyFields.map(field => {
          return {
            type: field.type,
            isNullable: false,
            isList: field.isList,
            name: this.generateIntermediateModelSortKeyFieldName(firstModel, field),
            directives: [],
          };
        }),
        {
          type: 'ID',
          isNullable: false,
          isList: false,
          name: secondModelKeyFieldName,
          directives: [
            {
              name: 'index',
              arguments: {
                name: 'by' + secondModel.name,
                sortKeyFields: secondModelSortKeyFields.map(f => this.generateIntermediateModelSortKeyFieldName(secondModel, f)),
              },
            },
          ],
        },
        ...secondModelSortKeyFields.map(field => {
          return {
            type: field.type,
            isNullable: false,
            isList: field.isList,
            name: this.generateIntermediateModelSortKeyFieldName(secondModel, field),
            directives: [],
          };
        }),
        {
          type: firstModel.name,
          isNullable: false,
          isList: false,
          name: camelCase(firstModel.name),
          directives: [{ name: 'belongsTo', arguments: { fields: [firstModelKeyFieldName] } }],
        },
        {
          type: secondModel.name,
          isNullable: false,
          isList: false,
          name: camelCase(secondModel.name),
          directives: [{ name: 'belongsTo', arguments: { fields: [secondModelKeyFieldName] } }],
        },
      ],
    };

    return intermediateModel;
  }