js-yaml#safeDump TypeScript Examples

The following examples show how to use js-yaml#safeDump. 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 next-basics with GNU General Public License v3.0 7 votes vote down vote up
safeDumpField = (value: any, field: string): string | undefined => {
  let result;
  try {
    result = safeDump(value, {
      indent: 2,
      schema: JSON_SCHEMA,
      skipInvalid: true,
      noRefs: true,
      noCompatMode: true,
    });
  } catch (e) {
    // eslint-disable-next-line no-console
    console.warn(value, `Illegal ${field}`);
  }
  return result;
}
Example #2
Source File: utils.tsx    From next-basics with GNU General Public License v3.0 7 votes vote down vote up
export function yamlStringify(value: unknown, indent = 2) {
  return safeDump(value, {
    indent,
    schema: JSON_SCHEMA,
    skipInvalid: true,
    noRefs: true,
    noCompatMode: true,
  });
}
Example #3
Source File: TestProject.ts    From yarn-plugins with MIT License 6 votes vote down vote up
public static async setup(): Promise<TestProject> {
    const dir = await tmp.dir();
    const pluginBundles = await globby('packages/*/bundles/**/*.js', {
      cwd: PROJECT_DIR,
    });
    const plugins = pluginBundles.map((src) => ({
      src,
      name: '@yarnpkg/' + basename(src, extname(src)),
      dest: posix.join('.yarn', 'plugins', ...src.split(sep).slice(3)),
    }));

    for (const path of plugins) {
      await copy(join(PROJECT_DIR, path.src), join(dir.path, path.dest));
    }

    const yarnConfig = safeLoad(
      await readFile(join(PROJECT_DIR, '.yarnrc.yml'), 'utf8'),
    ) as Record<string, unknown>;

    // Create .yarnrc.yml
    await outputFile(
      join(dir.path, '.yarnrc.yml'),
      safeDump({
        yarnPath: join(PROJECT_DIR, yarnConfig.yarnPath as string),
        plugins: plugins.map((plugin) => ({
          path: plugin.dest,
          spec: plugin.name,
        })),
      }),
    );

    // Create package.json
    await outputJSON(join(dir.path, 'package.json'), {
      private: true,
      workspaces: ['packages/*'],
    });

    return new TestProject(dir);
  }
Example #4
Source File: yamlUtils.ts    From amazon-states-language-service with MIT License 6 votes vote down vote up
export function convertJsonSnippetToYaml(snippetText: string) {
    // Convert to YAML with indendation of 1 space
    return safeDump(safeLoad(snippetText), { indent: 1 })
        // Remove quotation marks
        .replace(/[']/g, '')
        .split('\n')
        // For each line replace left padding spaces with tabs
        .map(line => {
            if (line.length) {
                let numOfSpaces = 0

                // Count number of spaces that the line begins with
                for (const char of line) {
                    if (char === ' ') {
                        numOfSpaces++
                    } else {
                        break
                    }
                }

                // Convert each space to tab character. Even though tab carracters are not valid yaml whitespace characters
                // the vscode will convert them to the correct number of spaces according to user preferences.
                return '\t'.repeat(numOfSpaces) + line.slice(numOfSpaces, line.length)
            } else {
                return line
            }
        })
        .join('\n')
}
Example #5
Source File: editor.ts    From che-dashboard-next with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Provides a devfile stringify function.
 */
export default function stringify(devfile: che.WorkspaceDevfile | undefined): string {
  if (!devfile) {
    return '';
  }
  return safeDump(devfile as che.WorkspaceDevfile, { lineWidth, sortKeys });
}
Example #6
Source File: processor.ts    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function yamlStringify(value: unknown, indent = 2) {
  return safeDump(value, {
    indent,
    schema: JSON_SCHEMA,
    skipInvalid: true,
    noRefs: true,
    noCompatMode: true,
  });
}
Example #7
Source File: processor.ts    From next-basics with GNU General Public License v3.0 6 votes vote down vote up
export function yamlStringify(value: unknown, indent = 2): string {
  try {
    return safeDump(value, {
      indent,
      schema: JSON_SCHEMA,
      skipInvalid: true,
      noRefs: true,
      noCompatMode: true,
    });
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(e);
  }
}
Example #8
Source File: getRequestExampleOfYaml.ts    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function getRequestExampleOfYaml(
  contractData: ContractData,
  curExample: Example
): any {
  const result: any = {};
  const uri = contractData.endpoint.uri;

  const uriRegex = new RegExp(uri.replace(/\/:[@_-\w]+/g, "/([@_-\\w]+)"));

  const path = curExample.request.uri;

  const uriMatch = path.match(uriRegex);

  if (uriMatch) {
    result.uriParams = uriMatch.slice(1);
  } else {
    result.uriParams = [];
  }

  const queryMatch = path.match(/\w+\?(.*)$/);

  if (queryMatch) {
    const [, q] = queryMatch;
    result.queryParams = {};
    q.split("&")?.forEach((item: any) => {
      const [key, value] = item.split("=");
      result.queryParams[key] = value;
    });
  }

  try {
    // istanbul ignore else
    if (curExample.request.body) {
      const body = JSON.parse(curExample.request.body);
      result.data = body;
    }
  } catch (error) {
    // istanbul ignore next
    // eslint-disable-next-line no-console
    console.error(error);
  }

  const args = compact([
    ...result.uriParams,
    isEmpty(result.data) ? null : result.data,
    result.queryParams,
  ]);

  return safeDump(args, {
    indent: 2,
    schema: JSON_SCHEMA,
    skipInvalid: true,
    noRefs: true,
    noCompatMode: true,
  });
}
Example #9
Source File: ScanBricksAndTemplates.ts    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function ScanBricksAndTemplates({
  storyboard,
  version,
  dependencies,
}: ScanBricksAndTemplatesParams): ScanBricksAndTemplatesResult {
  const processors = scanProcessorsInStoryboard(storyboard);
  const { bricks, customApis } = scanStoryboard(storyboard);
  const templates = scanTemplatesInStoryboard(storyboard);

  const legacyCustomApis: string[] = [];
  const flowApis: string[] = [];

  for (const api of customApis) {
    (api.includes(":") ? flowApis : legacyCustomApis).push(api);
  }

  let contractData: string;
  if (version && storyboard.app) {
    const dependenciesMap = new Map(
      dependencies?.map(({ name, constraint }) => [name, constraint]) ?? []
    );

    const deps: DependContract[] = [];
    for (const api of flowApis) {
      const [contract, v] = api.split(":");
      deps.push({
        type: "contract",
        contract: contract.replace("@", "."),
        version: v,
      });
    }

    for (const brick of bricks) {
      deps.push({
        type: "brick",
        brick,
        version: dependenciesMap.get(`${brick.split(".")[0]}-NB`) ?? "*",
      });
    }

    for (const template of templates) {
      deps.push({
        type: "template",
        template,
        version: dependenciesMap.get(`${template.split(".")[0]}-NT`) ?? "*",
      });
    }

    const contracts: ImplementedContract[] = [
      {
        type: "route",
        path: storyboard.app.homepage,
        version,
        deps,
      },
    ];
    contractData = safeDump(
      { contracts },
      {
        indent: 2,
        schema: JSON_SCHEMA,
        skipInvalid: true,
        noRefs: true,
        noCompatMode: true,
      }
    );
  }

  return {
    apis: mapCustomApisToNameAndNamespace(legacyCustomApis),
    bricks,
    templates,
    processors,
    processorPackages: uniq(
      // The package name should always be the param-case of processor's namespace.
      processors.map((item) => paramCase(item.split(".")[0]))
    ),
    contractData,
  };
}
Example #10
Source File: aslYamlLanguageService.ts    From amazon-states-language-service with MIT License 4 votes vote down vote up
getLanguageService = function(params: LanguageServiceParams, schema: JSONSchema, aslLanguageService: LanguageService): LanguageService {
    const builtInParams = {}

    const languageService = getLanguageServiceVscode({
        ...params,
        ...builtInParams,
    })

    const requestServiceMock = async function(uri: string): Promise<string> {
        return new Promise<string>(c => {
            c(JSON.stringify(schema))
        })
    }
    const schemaService = new YAMLSchemaService(requestServiceMock, params.workspaceContext)
    // initialize schema
    schemaService.registerExternalSchema(LANGUAGE_IDS.YAML, ['*'], schema)
    schemaService.getOrAddSchemaHandle(LANGUAGE_IDS.YAML, schema)

    const completer = new YAMLCompletion(schemaService)

    languageService.doValidation = async function(
        textDocument: TextDocument
    ) {
        const yamlDocument: YAMLDocument = parseYAML(textDocument.getText())
        const validationResult: Diagnostic[] = []

        for (const currentYAMLDoc of yamlDocument.documents) {
            const validation = await aslLanguageService.doValidation(textDocument, currentYAMLDoc)
            validationResult.push(
                ...currentYAMLDoc.errors
                    .concat(currentYAMLDoc.warnings)
                    .map(err => convertYAMLDiagnostic(err, textDocument))
            )
            validationResult.push(...validation)
        }

        return validationResult
    }

    languageService.doComplete = async function(
        document: TextDocument,
        position: Position
    ): Promise<CompletionList> {
        const {
            modifiedDocText,
            tempPositionForCompletions,
            startPositionForInsertion,
            endPositionForInsertion,
            shouldPrependSpace
        } = processYamlDocForCompletion(document, position)

        const processedDocument = TextDocument.create(document.uri, document.languageId, document.version, modifiedDocText)

        const offsetIntoOriginalDocument = document.offsetAt(position)
        const offsetIntoProcessedDocument = processedDocument.offsetAt(tempPositionForCompletions)

        const processedYamlDoc: YAMLDocument = parseYAML(modifiedDocText)
        const currentDoc = matchOffsetToDocument(offsetIntoProcessedDocument, processedYamlDoc)

        if (!currentDoc) {
            return { items: [], isIncomplete: false }
        }

        const positionForDoComplete = {...tempPositionForCompletions} // Copy position to new object since doComplete modifies the position
        const yamlCompletions = await completer.doComplete(processedDocument, positionForDoComplete, false)
        // yaml-language-server does not output correct completions for retry/catch
        // we need to overwrite the text
        function updateCompletionText(item: CompletionItem, text: string) {
            item.insertText = text

            if (item.textEdit) {
                item.textEdit.newText = text
            }
        }

        yamlCompletions.items.forEach(item => {
            if (item.label === 'Catch') {
                updateCompletionText(item, CATCH_INSERT)
            } else if (item.label === 'Retry') {
                updateCompletionText(item, RETRY_INSERT)
            }
        })

        const { isDirectChildOfStates, isWithinCatchRetryState, hasCatchPropSibling, hasRetryPropSibling } = getOffsetData(document, offsetIntoOriginalDocument)

        const aslOptions: ASLOptions = {
            ignoreColonOffset: true,
            shouldShowStateSnippets: isDirectChildOfStates,
            shouldShowErrorSnippets: {
                retry: isWithinCatchRetryState && !hasRetryPropSibling,
                catch: isWithinCatchRetryState && !hasCatchPropSibling
            }
        }

        const aslCompletions: CompletionList  = doCompleteAsl(processedDocument, tempPositionForCompletions, currentDoc, yamlCompletions, aslOptions)

        const modifiedAslCompletionItems: CompletionItem[] = aslCompletions.items.map(completionItem => {
            const completionItemCopy = {...completionItem} // Copy completion to new object to avoid overwriting any snippets

            if (completionItemCopy.insertText && completionItemCopy.kind === CompletionItemKind.Snippet && document.languageId === LANGUAGE_IDS.YAML) {
                completionItemCopy.insertText = convertJsonSnippetToYaml(completionItemCopy.insertText)
            } else {
                const currentTextEdit = completionItemCopy.textEdit

                if (currentTextEdit) {
                    if (shouldPrependSpace) {
                        if (currentTextEdit.newText && currentTextEdit.newText.charAt(0) !== ' ') {
                            currentTextEdit.newText = ' ' + currentTextEdit.newText
                        }
                        if (completionItemCopy.insertText && completionItemCopy.insertText.charAt(0) !== ' ') {
                            completionItemCopy.insertText = ' ' + completionItemCopy.insertText
                        }
                    }

                    currentTextEdit.range.start = startPositionForInsertion
                    currentTextEdit.range.end = endPositionForInsertion

                    // Completions that include both a key and a value should replace everything right of the cursor.
                    if (completionItemCopy.kind === CompletionItemKind.Property) {
                        currentTextEdit.range.end = {
                            line: endPositionForInsertion.line,
                            character: document.getText().length
                        }
                    }
                }
            }

            return completionItemCopy
        })

        const modifiedAslCompletions: CompletionList = {
            isIncomplete: aslCompletions.isIncomplete,
            items: modifiedAslCompletionItems
        }

        return Promise.resolve(modifiedAslCompletions)
    }

    languageService.doHover = function(
        document: TextDocument,
        position: Position
    ): Thenable<Hover | null> {
        const doc = parseYAML(document.getText())
        const offset = document.offsetAt(position)
        const currentDoc = matchOffsetToDocument(offset, doc)
        if (!currentDoc) {
            // tslint:disable-next-line: no-null-keyword
            return Promise.resolve(null)
        }

        const currentDocIndex = doc.documents.indexOf(currentDoc)
        currentDoc.currentDocIndex = currentDocIndex

        return aslLanguageService.doHover(document, position, currentDoc)
    }

    languageService.format = function(
        document: TextDocument,
        range: Range,
        options: FormattingOptions
    ): TextEdit[] {
        try {
            const text = document.getText()
            const formatted = safeDump(safeLoad(text), { indent: options.tabSize })

            return [TextEdit.replace(Range.create(Position.create(0, 0), document.positionAt(text.length)), formatted)]
        } catch (error) {
            return []
        }
    }

    languageService.findDocumentSymbols = function(document: TextDocument): SymbolInformation[] {
        const doc = parseYAML(document.getText())
        if (!doc || doc.documents.length === 0) {
            return []
        }

        let results: any[] = []
        for (const yamlDoc of doc.documents) {
            if (yamlDoc.root) {
                results = results.concat(aslLanguageService.findDocumentSymbols(document, yamlDoc))
            }
        }

        return results
    }

    languageService.findDocumentSymbols2 = function(document: TextDocument): DocumentSymbol[] {
        const doc = parseYAML(document.getText())
        if (!doc || doc.documents.length === 0) {
            return []
        }

        let results: any[] = []
        for (const yamlDoc of doc.documents) {
            if (yamlDoc.root) {
                results = results.concat(aslLanguageService.findDocumentSymbols2(document, yamlDoc))
            }
        }

        return results
    }

    return languageService
}