js-yaml#JSON_SCHEMA TypeScript Examples

The following examples show how to use js-yaml#JSON_SCHEMA. 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.ts    From next-basics with GNU General Public License v3.0 7 votes vote down vote up
safeLoadField = (value: string, field: string): any => {
  let result;
  try {
    result = safeLoad(value, {
      schema: JSON_SCHEMA,
      json: true,
    });
  } catch (e) {
    // eslint-disable-next-line no-console
    console.warn(value, `Illegal ${field}`);
    return {
      help: `${field} is error`,
      $$validateStatus: true,
    };
  }
  return result;
}
Example #3
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 #4
Source File: filesv2.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
function serializeModuleProps(moduleProps: SchemaModuleProps) {
  const { version, imports, schemas } = moduleProps;
  // TODO: filter out imported schemas
  const out: any = {
    version,
    imports: [],
    schemas: _.values(schemas).map((ent) =>
      SchemaUtils.serializeSchemaProps(ent)
    ),
  };
  if (imports) {
    out.imports = imports;
  }
  return YAML.dump(out, { schema: JSON_SCHEMA });
}
Example #5
Source File: filesv2.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
function serializeModuleOpts(moduleOpts: SchemaModuleOpts) {
  const { version, imports, schemas } = _.defaults(moduleOpts, {
    imports: [],
  });
  const out = {
    version,
    imports,
    schemas: _.values(schemas).map((ent) =>
      SchemaUtils.serializeSchemaProps(ent)
    ),
  };
  return YAML.dump(out, { schema: JSON_SCHEMA });
}
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 yaml(value: string): unknown {
  let result;
  try {
    result = safeLoad(value, { schema: JSON_SCHEMA, json: true });
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(e);
  }
  return result;
}
Example #8
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 #9
Source File: MagicBrick.tsx    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function MagicBrick(props: MagicBrickProps): React.ReactElement {
  const [useBrickConf, setUseBrickConf] = useState<UseSingleBrickConf>();

  useEffect(() => {
    async function fetchData(): Promise<void> {
      const magicBrickConfigMap = await getRuntime().getMagicBrickConfigMapAsync();
      if (magicBrickConfigMap.has(props.showType)) {
        const data = magicBrickConfigMap.get(props.showType);
        try {
          const $$parsedProperties = data.properties
            ? safeLoad(data.properties, { schema: JSON_SCHEMA, json: true })
            : {};
          const parsedTransform = data.transform
            ? safeLoad(data.transform, { schema: JSON_SCHEMA, json: true })
            : {};
          const parsedEvents = data.events
            ? safeLoad(data.events, { schema: JSON_SCHEMA, json: true })
            : {};
          const useBrickConf: UseSingleBrickConf = {
            brick: data.brick,
            properties: $$parsedProperties as Record<string, unknown>,
            transform: parsedTransform as GeneralTransform,
            events: parsedEvents as BrickEventsMap,
          };
          await developHelper.loadDynamicBricksInBrickConf(
            useBrickConf as BrickConf
          );
          setUseBrickConf(useBrickConf);
        } catch (e) {
          // eslint-disable-next-line no-console
          console.error(
            `请检查 ${props.showType} 的配置信息是否为有效的yaml数据`
          );
        }
      } else {
        // eslint-disable-next-line no-console
        console.error(`请检查是否存在 ${props.showType} 对应的配置信息`);
      }
    }
    if (props.showType) {
      fetchData();
    }
  }, [props.showType]);

  return (
    <>
      {useBrickConf && (
        <BrickAsComponent useBrick={useBrickConf} data={props.data} />
      )}
    </>
  );
}
Example #10
Source File: processor.ts    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
export function yaml(value: string): any {
  return safeLoad(value, { schema: JSON_SCHEMA, json: true });
}
Example #11
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 #12
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 #13
Source File: buildStoryboardV2.ts    From next-basics with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Refined building storyboard with graph api response.
 */
export function buildStoryboardV2(data: BuildInfoV2): StoryboardToBuild {
  const keepIds = data.options?.keepIds;
  const ctx: BuildContext = {
    keepIds,
  };

  const routes = buildRoutes(data.routeList, ctx);

  const customTemplates = data.templateList?.map((template) => ({
    name: template.templateId,
    proxy: template.proxy,
    state: template.state,
    bricks: buildBricks(template.children, ctx) as BrickConfInTemplate[],
    ...(keepIds
      ? {
          [symbolForNodeId]: template.id,
        }
      : undefined),
  }));

  const menus = data.menus?.map(normalizeMenu);

  const i18n = data.i18n?.reduce(
    (acc, node) => {
      acc.en[node.name] = node.en;
      acc.zh[node.name] = node.zh;
      return acc;
    },
    {
      en: {},
      zh: {},
    } as Record<string, Record<string, string>>
  );

  const functions = data.functions?.map((fn) => ({
    name: fn.name,
    source: fn.source,
    typescript: fn.typescript,
  }));

  const meta = {
    customTemplates,
    menus,
    i18n,
    functions,
    mocks: data.mocks,
  };

  // 基于当前最新的 storyboard 扫描 contract 信息
  const { contractData: contractStr } = ScanBricksAndTemplates({
    storyboard: {
      app: data.app,
      routes,
      meta,
    },
    version: "workspace",
    dependencies: data.dependencies,
  });

  const deps: DependContract[] = get(
    safeLoad(contractStr, { schema: JSON_SCHEMA, json: true }),
    "contracts[0].deps"
  );

  return {
    routes,
    meta: {
      ...meta,
      contracts: deps?.filter(
        (item) => item.type === "contract"
      ) as DependContractOfApi[],
    },
    dependsAll: data.dependsAll,
  };
}