export function createTextTransformerPlugin()

in packages/extensions/core/src/lib/plugins/transformer/transformer.ts [82:165]


export function createTextTransformerPlugin(): PipelinePlugin {
  // create a lightweight text transformer.
  return async (config, input, sink) => {
    // get directives as concrete objects.

    // text transforms are always 'where: $' or no where clause at all.
    const directives = config.resolveDirectives(
      (x) => x.transform.length > 0 && (x.where.length === 0 || (x.where.length === 1 && x.where[0] === "$")),
    );

    if (directives.length === 0) {
      return input;
    }

    const result: Array<DataHandle> = [];
    for (const file of await input.enum()) {
      const inputHandle = await input.read(file);
      if (inputHandle) {
        const documentId = `/${inputHandle.description || inputHandle.key}`;
        let contents: string | undefined = undefined;
        let modified = false;

        for (const directive of directives) {
          if (
            directive.from.length === 0 ||
            directive.from.find(
              (each) =>
                each === inputHandle.artifactType || // artifact by type (ie, source-file-csharp)
                documentId.endsWith(`/${each}`) || // by name (ie, Get_AzAdSomething.cs)
                documentId.match(new RegExp(`/.+/${each}$`)),
            )
          ) {
            // by regex (ie, Get-AzAd.*.cs)

            // if the file should be processed, run it thru
            for (const transform of directive.transform) {
              // grab the contents (don't extend the cache tho')
              contents = contents === undefined ? await inputHandle.ReadData(true) : contents;

              config.debug(`Running text transform '${directive.from}/${directive.reason}' on ${inputHandle.key} `);

              const output = evalDirectiveTransform(transform, {
                config,
                value: contents,
                doc: inputHandle,
                path: [],
                documentPath: inputHandle.key,
              });

              if (typeof output !== "string") {
                throw new Error(
                  [
                    `Unexpected result from directive, expected a string but got '${typeof output}'.`,
                    "Transform code:\n",
                    directive.transform,
                  ].join("\n"),
                );
              }

              if (output !== contents) {
                modified = true;
                contents = output;
              }
            }
          }
        }

        if (modified) {
          result.push(
            await sink.writeData(
              inputHandle.description,
              contents || "",
              inputHandle.identity,
              inputHandle.artifactType,
            ),
          );
        } else {
          result.push(await sink.forward(inputHandle.description, inputHandle));
        }
      }
    }
    return new QuickDataSource(result, input.pipeState);
  };
}