import { importShared } from './__federation_fn_import-C3oBjoRC.js';
import { g as get, s as set, c as appendErrors, j as jsxRuntimeExports } from './index.esm-BdtKQ4f_.js';
import { l as parse, m as parseAsync, K as $ZodError } from './registries-Tz_dluz3.js';
import { c as createRateLimitPluginDefinitionSchema, a as createRateLimitPartialDefinition } from './plugin-definition-D40BqcHC.js';

const r=(t,r,o)=>{if(t&&"reportValidity"in t){const s=get(o,r);t.setCustomValidity(s&&s.message||""),t.reportValidity();}},o=(e,t)=>{for(const o in t.fields){const s=t.fields[o];s&&s.ref&&"reportValidity"in s.ref?r(s.ref,o,e):s&&s.refs&&s.refs.forEach(t=>r(t,o,e));}},s$1=(r,s)=>{s.shouldUseNativeValidation&&o(r,s);const n={};for(const o in r){const f=get(s.fields,o),c=Object.assign(r[o]||{},{ref:f&&f.ref});if(i$1(s.names||Object.keys(r),o)){const r=Object.assign({},get(n,o));set(r,"root",c),set(n,o,r);}else set(n,o,c);}return n},i$1=(e,t)=>{const r=n(t);return e.some(e=>n(e).match(`^${r}\\.\\d+`))};function n(e){return e.replace(/\]|\[/g,"")}

function t(r,e){try{var o=r();}catch(r){return e(r)}return o&&o.then?o.then(void 0,e):o}function s(r,e){for(var n={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("unionErrors"in t){var u=t.unionErrors[0].errors[0];n[a]={message:u.message,type:u.code};}else n[a]={message:i,type:s};if("unionErrors"in t&&t.unionErrors.forEach(function(e){return e.errors.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[t.code];n[a]=appendErrors(a,e,n,s,f?[].concat(f,t.message):t.message);}r.shift();}return n}function i(r,e){for(var n={};r.length;){var t=r[0],s=t.code,i=t.message,a=t.path.join(".");if(!n[a])if("invalid_union"===t.code&&t.errors.length>0){var u=t.errors[0][0];n[a]={message:u.message,type:u.code};}else n[a]={message:i,type:s};if("invalid_union"===t.code&&t.errors.forEach(function(e){return e.forEach(function(e){return r.push(e)})}),e){var c=n[a].types,f=c&&c[t.code];n[a]=appendErrors(a,e,n,s,f?[].concat(f,t.message):t.message);}r.shift();}return n}function a(o$1,a,u){if(void 0===u&&(u={}),function(r){return "_def"in r&&"object"==typeof r._def&&"typeName"in r._def}(o$1))return function(n,i,c){try{return Promise.resolve(t(function(){return Promise.resolve(o$1["sync"===u.mode?"parse":"parseAsync"](n,a)).then(function(e){return c.shouldUseNativeValidation&&o({},c),{errors:{},values:u.raw?Object.assign({},n):e}})},function(r){if(function(r){return Array.isArray(null==r?void 0:r.issues)}(r))return {values:{},errors:s$1(s(r.errors,!c.shouldUseNativeValidation&&"all"===c.criteriaMode),c)};throw r}))}catch(r){return Promise.reject(r)}};if(function(r){return "_zod"in r&&"object"==typeof r._zod}(o$1))return function(s,c,f){try{return Promise.resolve(t(function(){return Promise.resolve(("sync"===u.mode?parse:parseAsync)(o$1,s,a)).then(function(e){return f.shouldUseNativeValidation&&o({},f),{errors:{},values:u.raw?Object.assign({},s):e}})},function(r){if(function(r){return r instanceof $ZodError}(r))return {values:{},errors:s$1(i(r.issues,!f.shouldUseNativeValidation&&"all"===f.criteriaMode),f)};throw r}))}catch(r){return Promise.reject(r)}};throw new Error("Invalid input: not a Zod schema")}

const {applyMergedDefinition,diffDefinition,FeatureUtils,PluginUtils} = await importShared('@baseplate-dev/project-builder-lib');

const {DefinitionDiffAlert,FeatureComboboxFieldController,useBlockUnsavedChangesNavigate,useDefinitionSchema,useProjectDefinition,useResettableForm} = await importShared('@baseplate-dev/project-builder-lib/web');

const {FormActionBar,SectionList,SectionListSection,SectionListSectionContent,SectionListSectionDescription,SectionListSectionHeader,SectionListSectionTitle} = await importShared('@baseplate-dev/ui-components');
const {useMemo} = await importShared('react');
function RateLimitDefinitionEditor({
  definition: pluginMetadata,
  metadata,
  onSave
}) {
  const { definition, definitionContainer, saveDefinitionWithFeedback } = useProjectDefinition();
  const rateLimitPluginDefinitionSchema = useDefinitionSchema(
    createRateLimitPluginDefinitionSchema
  );
  const defaultValues = useMemo(() => {
    if (pluginMetadata?.config) {
      return pluginMetadata.config;
    }
    const defaultFeatureRef = FeatureUtils.getFeatureIdByNameOrDefault(
      definition,
      "utilities"
    );
    return {
      rateLimitFeatureRef: defaultFeatureRef,
      rateLimitOptions: {}
    };
  }, [definition, pluginMetadata?.config]);
  const form = useResettableForm({
    resolver: a(rateLimitPluginDefinitionSchema),
    defaultValues
  });
  const { control, reset, handleSubmit } = form;
  const pluginConfig = pluginMetadata?.config;
  const diff = useMemo(() => {
    const featureRef = pluginConfig?.rateLimitFeatureRef ?? "";
    if (!featureRef) return void 0;
    const featureName = FeatureUtils.resolveFeatureName(definition, featureRef);
    const partialDef = createRateLimitPartialDefinition(featureName);
    return diffDefinition(
      definitionContainer.schema,
      definitionContainer.definition,
      partialDef
    );
  }, [definitionContainer, definition, pluginConfig?.rateLimitFeatureRef]);
  const onSubmit = handleSubmit(
    (data) => saveDefinitionWithFeedback(
      (draftConfig) => {
        const featureName = FeatureUtils.resolveFeatureName(
          draftConfig,
          data.rateLimitFeatureRef
        );
        const partialDef = createRateLimitPartialDefinition(featureName);
        applyMergedDefinition(definitionContainer, partialDef)(draftConfig);
        PluginUtils.setPluginConfig(
          draftConfig,
          metadata,
          {
            ...data,
            rateLimitFeatureRef: FeatureUtils.getFeatureIdByNameOrThrow(
              draftConfig,
              featureName
            )
          },
          definitionContainer
        );
      },
      {
        successMessage: "Successfully saved Rate Limiting configuration!",
        onSuccess: () => {
          onSave();
        }
      }
    )
  );
  useBlockUnsavedChangesNavigate({ control, reset, onSubmit });
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ratelimit:relative ratelimit:flex ratelimit:h-full ratelimit:flex-1 ratelimit:flex-col ratelimit:gap-4 ratelimit:overflow-hidden", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      className: "ratelimit:mb-[--action-bar-height] ratelimit:flex ratelimit:flex-1 ratelimit:overflow-y-auto",
      style: {
        "--action-bar-height": "52px"
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "form",
        {
          onSubmit,
          className: "ratelimit:max-w-6xl ratelimit:flex-1",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "ratelimit:pb-16", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionList, { children: [
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSection, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionHeader, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionTitle, { children: "General Settings" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionDescription, { children: "Configure the general settings for the rate limiting plugin." })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionContent, { className: "ratelimit:space-y-6", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  FeatureComboboxFieldController,
                  {
                    label: "Feature Path",
                    name: "rateLimitFeatureRef",
                    control,
                    canCreate: true,
                    description: "Specify the feature path where the rate limiting model will be created"
                  }
                ) })
              ] }),
              /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSection, { children: [
                /* @__PURE__ */ jsxRuntimeExports.jsxs(SectionListSectionHeader, { children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionTitle, { children: "Rate Limiting Models" }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionDescription, { children: "The plugin will automatically configure the models it needs for rate limiting storage." })
                ] }),
                /* @__PURE__ */ jsxRuntimeExports.jsx(SectionListSectionContent, { className: "ratelimit:space-y-6", children: diff ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                  DefinitionDiffAlert,
                  {
                    diff,
                    upToDateMessage: "All required models are already configured correctly. No changes needed."
                  }
                ) : /* @__PURE__ */ jsxRuntimeExports.jsx("p", { className: "ratelimit:text-sm ratelimit:text-muted-foreground", children: "Save to create the RateLimiterFlexible model in your project." }) })
              ] })
            ] }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              FormActionBar,
              {
                form,
                allowSaveWithoutDirty: !pluginMetadata || (diff?.hasChanges ?? false)
              }
            )
          ]
        }
      )
    }
  ) });
}

const {createPluginModule,webConfigSpec} = await importShared('@baseplate-dev/project-builder-lib');
const web = createPluginModule({
  name: "web",
  dependencies: {
    webConfig: webConfigSpec
  },
  initialize: ({ webConfig }, { pluginKey }) => {
    webConfig.components.set(pluginKey, RateLimitDefinitionEditor);
  }
});

export { web as default };
//# sourceMappingURL=__federation_expose_rate-limitCoreWeb-DWcVtI8y.js.map
