From c843319c3e43a047d0e4751f663df6da4dedcb82 Mon Sep 17 00:00:00 2001 From: Steve Manuel Date: Thu, 22 Aug 2024 15:17:42 -0600 Subject: [PATCH] fix: add std import when needed --- src/index.ts | 18 +++++++++++++++++- template/src/main.zig.ejs | 1 + 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 08f9130..1239970 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ import ejs from "ejs"; -import { getContext, helpers, Property } from "@dylibso/xtp-bindgen"; +import { getContext, helpers, Property, XtpSchema } from "@dylibso/xtp-bindgen"; function toZigType(property: Property, pkg?: string): string { if (property.$ref) return (pkg ? `${pkg}.` : "") + property.$ref.name; @@ -39,6 +39,21 @@ function pointerToZigType(property: Property) { return `*${typ}`; } +function addStdImport(schema: XtpSchema) { + // in the generated `main.zig` this would include a reference to + // std.json.ArrayHashMap and std.json.Value, so we import "std". + const exportHasJsonObject = schema.exports.some((f) => { + return (f.input?.contentType === "application/json" && + f.input.type === "object") || + (f.output?.contentType === "application/json" && + f.output.type === "object"); + }); + + return exportHasJsonObject /* || others here */ + ? 'const std = @import("std");' + : null; +} + function makeStructName(s: string) { const cap = s.charAt(0).toUpperCase(); if (s.charAt(0) === cap) { @@ -57,6 +72,7 @@ export function render() { toZigType, pointerToZigType, makeStructName, + addStdImport, }; const output = ejs.render(tmpl, ctx); diff --git a/template/src/main.zig.ejs b/template/src/main.zig.ejs index 23381d5..6a41f57 100644 --- a/template/src/main.zig.ejs +++ b/template/src/main.zig.ejs @@ -1,3 +1,4 @@ +<%- addStdImport(schema) %> const schema = @import("schema.zig"); <%- schema.imports && schema.imports.length > 0 ? "const Host = schema.Host;" : null %>