@proofkit/cli 2.0.0-beta.23 → 2.0.0-beta.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/add-h15IdCWp.js +57 -0
  3. package/dist/add-h15IdCWp.js.map +1 -0
  4. package/dist/{addPackageDependency-BGZl7xc5.js → addPackageDependency-BUJ8tT5i.js} +2 -2
  5. package/dist/{addPackageDependency-BGZl7xc5.js.map → addPackageDependency-BUJ8tT5i.js.map} +1 -1
  6. package/dist/{consts-BZnOMxpW.js → consts-CE9CE6Fo.js} +4 -4
  7. package/dist/{consts-BZnOMxpW.js.map → consts-CE9CE6Fo.js.map} +1 -1
  8. package/dist/{deploy-D25sPO7K.js → deploy-BJryOaec.js} +3 -3
  9. package/dist/{deploy-D25sPO7K.js.map → deploy-BJryOaec.js.map} +1 -1
  10. package/dist/errors-DxuuVXoQ.js +2 -0
  11. package/dist/errors-DxuuVXoQ.js.map +1 -0
  12. package/dist/{fmdapi-BO4QL0F8.js → fmdapi-D4f7TrLy.js} +2 -2
  13. package/dist/{fmdapi-BO4QL0F8.js.map → fmdapi-D4f7TrLy.js.map} +1 -1
  14. package/dist/{fmdapi-DyRYZWzI.js → fmdapi-H4o2qGE2.js} +3 -3
  15. package/dist/{fmdapi-DyRYZWzI.js.map → fmdapi-H4o2qGE2.js.map} +1 -1
  16. package/dist/{getUserPkgManager-Cph_6l1P.js → getUserPkgManager-CZwrE7fs.js} +1 -1
  17. package/dist/{getUserPkgManager-Cph_6l1P.js.map → getUserPkgManager-CZwrE7fs.js.map} +1 -1
  18. package/dist/{globalOptions-CkqEi9uC.js → globalOptions-C6fknjPB.js} +1 -1
  19. package/dist/{globalOptions-CkqEi9uC.js.map → globalOptions-C6fknjPB.js.map} +1 -1
  20. package/dist/{index-DALPpGd1.d.ts → index-D9Y-xAF1.d.ts} +124 -42
  21. package/dist/index-D9Y-xAF1.d.ts.map +1 -0
  22. package/dist/index.js +10 -7
  23. package/dist/index.js.map +1 -1
  24. package/dist/{logger-DCEXcH26.js → logger-DxbfijxS.js} +1 -1
  25. package/dist/{logger-DCEXcH26.js.map → logger-DxbfijxS.js.map} +1 -1
  26. package/dist/{parseSettings-DJ2m9sgJ.js → parseSettings-xU5Rw3Ne.js} +1 -1
  27. package/dist/{parseSettings-DJ2m9sgJ.js.map → parseSettings-xU5Rw3Ne.js.map} +1 -1
  28. package/dist/{proofkit-webviewer-73IB1OBU.js → proofkit-webviewer-Baa93FAx.js} +2 -2
  29. package/dist/{proofkit-webviewer-73IB1OBU.js.map → proofkit-webviewer-Baa93FAx.js.map} +1 -1
  30. package/dist/remove-COo1Ju8v.js +2 -0
  31. package/dist/remove-COo1Ju8v.js.map +1 -0
  32. package/dist/typegen-DrfVmQfx.js +2 -0
  33. package/dist/{typegen-DyXaif5O.js.map → typegen-DrfVmQfx.js.map} +1 -1
  34. package/dist/update-Cpyhj57Y.js +7 -0
  35. package/dist/{update-FX71y5b3.js.map → update-Cpyhj57Y.js.map} +1 -1
  36. package/dist/utils-DGwyHkvO.js +3 -0
  37. package/dist/{utils-DymV7zmv.js.map → utils-DGwyHkvO.js.map} +1 -1
  38. package/package.json +2 -2
  39. package/template/nextjs-mantine/package.json +2 -1
  40. package/template/nextjs-shadcn/package.json +2 -0
  41. package/template/vite-wv/package.json +2 -2
  42. package/dist/add-DrcID6d6.js +0 -57
  43. package/dist/add-DrcID6d6.js.map +0 -1
  44. package/dist/index-DALPpGd1.d.ts.map +0 -1
  45. package/dist/remove-BOCU6In3.js +0 -2
  46. package/dist/remove-BOCU6In3.js.map +0 -1
  47. package/dist/typegen-DyXaif5O.js +0 -2
  48. package/dist/update-FX71y5b3.js +0 -7
  49. package/dist/utils-DymV7zmv.js +0 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @proofgeist/kit
2
2
 
3
+ ## 2.0.0-beta.26
4
+
5
+ ### Patch Changes
6
+
7
+ - e3b25c3: Refocus the ProofKit CLI around project bootstrap and diagnostics by adding `doctor` and placeholder `prompt` commands, updating default guidance and docs, and switching scaffolded typegen scripts to package-native `@proofkit/typegen` commands.
8
+
9
+ ## 2.0.0-beta.25
10
+
11
+ ### Patch Changes
12
+
13
+ - 41c07ba: Auto-detect non-interactive terminals for CLI commands in CI, scripted runs, and coding-agent environments.
14
+ - 1096f3b: Improve `proofkit init` error handling by using tagged Effect-based CLI errors for expected failures, unifying user cancellation, and rendering cleaner top-level error output.
15
+ - e6d0c55: Improve local ProofKit MCP setup messaging during webviewer init by reporting the connected FileMaker file after retry and prompting to choose a file when multiple files are open.
16
+ - 46696e4: Require `proofkit init` to use an explicit local FileMaker file selection in non-interactive multi-file setups, and save the selected local file into the generated typegen config.
17
+ - Updated dependencies [7b46a23]
18
+ - Updated dependencies [88242c2]
19
+ - @proofkit/typegen@1.1.0-beta.20
20
+
3
21
  ## 2.0.0-beta.23
4
22
 
5
23
  ### Minor Changes
@@ -0,0 +1,57 @@
1
+ import{a as e,c as t,f as n,l as r,m as i,n as a,o,p as s,r as c,s as l,t as u}from"./state-BVEcvFT3.js";import{a as d,r as f}from"./consts-CE9CE6Fo.js";import{s as p}from"./errors-DxuuVXoQ.js";import{a as ee,c as te,d as m,f as ne,i as h,l as re,n as g,o as _,p as v,r as y,s as ie,t as b,u as ae}from"./utils-DGwyHkvO.js";import{n as oe,t as se}from"./globalOptions-C6fknjPB.js";import{t as x}from"./logger-DxbfijxS.js";import{n as S,o as ce,r as le,s as ue,t as de}from"./parseSettings-xU5Rw3Ne.js";import{t as fe}from"./getUserPkgManager-CZwrE7fs.js";import{n as pe,r as me,t as C}from"./addPackageDependency-BUJ8tT5i.js";import{a as he,d as ge,f as w,i as _e,n as ve,o as ye,p as T,r as be,s as xe,t as Se,u as Ce}from"./fmdapi-H4o2qGE2.js";import{a as we,n as Te,o as Ee,t as De}from"./fmdapi-D4f7TrLy.js";import Oe,{readFileSync as ke,writeFileSync as Ae}from"node:fs";import E from"node:path";import{fileURLToPath as je}from"node:url";import Me from"dotenv";import D from"chalk";import{execa as Ne}from"execa";import O from"fs-extra";import Pe from"open";import Fe from"node:https";import k,{AxiosError as Ie}from"axios";import{Command as Le}from"commander";import{capitalize as Re,groupBy as ze,uniq as Be}from"es-toolkit";import Ve from"ora";import He,{SemVer as Ue}from"semver";import{execSync as We}from"node:child_process";import{StructureKind as Ge,SyntaxKind as A}from"ts-morph";import{glob as Ke}from"glob";import qe from"randomstring";import"jiti";import"fast-glob";import{createFetch as Je,createSchema as Ye}from"@better-fetch/fetch";import Xe from"handlebars";function Ze(e){for(let e of[`src/config/env.ts`,`src/lib/env.ts`,`src/env.ts`,`lib/env.ts`,`env.ts`,`config/env.ts`]){let t=E.join(c.projectDir,e);if(O.existsSync(t))return t}if(e===!1)return null;throw x.warn(`Could not find T3 env files. Run "proofkit add utils/t3-env" to initialize them.`),Error(`T3 env file not found`)}async function Qe({projectDir:e=c.projectDir,envs:t,envFileDescription:n,...r}){let i=Ze(),a=r.project??w(e),o=a.addSourceFileAtPath(i);if(!o)throw Error(`Schema file not found`);let s=o.getDescendantsOfKind(A.CallExpression).find(e=>e.getExpression().getText()===`createEnv`);if(!s)throw Error(`Could not find createEnv call in schema file. Make sure you have a valid env.ts file with createEnv setup.`);let l=s.getArguments()[0];if(!l)throw Error(`createEnv call is missing options argument`);let u=l.getDescendantsOfKind(A.PropertyAssignment).find(e=>e.getName()===`server`)?.getFirstDescendantByKind(A.ObjectLiteralExpression),d=l.getDescendantsOfKind(A.PropertyAssignment).find(e=>e.getName()===`client`)?.getFirstDescendantByKind(A.ObjectLiteralExpression),f=l.getDescendantsOfKind(A.PropertyAssignment).find(e=>e.getName()===`experimental__runtimeEnv`)?.getFirstDescendantByKind(A.ObjectLiteralExpression),p=t.filter(e=>e.type===`server`),ee=t.filter(e=>e.type===`client`);for(let e of p)u?.addPropertyAssignment({name:e.name,initializer:e.zodValue});for(let e of ee)d?.addPropertyAssignment({name:e.name,initializer:e.zodValue}),f?.addPropertyAssignment({name:e.name,initializer:`process.env.${e.name}`});let te=t.filter(e=>e.addToRuntimeEnv??!0).map(e=>`${e.name}=${e.defaultValue??``}`).join(`
2
+ `),m=E.join(e,`.env`);if(O.existsSync(m)){let t=O.readFileSync(m,`utf-8`),r=E.join(e,`.gitignore`);try{let t=``;O.existsSync(r)&&(t=O.readFileSync(r,`utf-8`)),t.includes(`.env`)||We(`echo ".env" >> "${r}"`,{cwd:e})}catch{}let i=`${t}
3
+ ${n?`# ${n}\n${te}`:te}
4
+ `;O.writeFileSync(m,i)}return r.project||await T(a),o}async function $e({...e}){let t=c.projectDir,n=S();if(n.ui===`shadcn`||n.reactEmail)return!1;O.ensureDirSync(E.join(t,`src/emails`)),C({dependencies:[`@react-email/components`,`@react-email/render`],devMode:!1,projectDir:t}),C({dependencies:[`react-email`,`@react-email/preview-server`],devMode:!0,projectDir:t});let r=O.readJSONSync(E.join(t,`package.json`));r.scripts||={},r.scripts[`email:preview`]=`email dev --port 3010 --dir=src/emails`,O.writeJSONSync(E.join(t,`package.json`),r,{spaces:2});let i=e.project??w(t);if(e.installServerFiles){let e=c.emailProvider;e===`plunk`?await et({project:i}):e===`resend`?await tt({project:i}):await O.copy(E.join(d,`template/extras/emailProviders/none/email.tsx`),E.join(t,`src/server/auth/email.tsx`))}return await O.copy(E.join(d,`template/extras/emailTemplates/generic.tsx`),E.join(t,`src/emails/generic.tsx`)),e.installServerFiles&&await O.copy(E.join(d,`template/extras/emailTemplates/auth-code.tsx`),E.join(t,`src/emails/auth-code.tsx`)),e.project||await T(i),ce({...n,reactEmail:!0,reactEmailServer:!!e.installServerFiles||n.reactEmailServer}),e.noInstall||await me({projectDir:t}),!0}async function et({project:e}){let t=c.projectDir;C({dependencies:[`@plunk/node`],devMode:!1,projectDir:t});let n;n=typeof c.apiKey==`string`?c.apiKey:a()?``:b(await v({message:`Enter your Plunk API key\n${D.dim(`Enter your Secret API Key from https://app.useplunk.com/settings/api`)}`})),n||x.warn(`You will need to add your Plunk API key to the .env file manually for your app to run.`),console.log(``),await Qe({projectDir:t,project:e,envs:[{name:`PLUNK_API_KEY`,zodValue:`z.string().startsWith("sk_")`,type:`server`,defaultValue:n}]}),await O.copy(E.join(d,`template/extras/emailProviders/plunk/service.ts`),E.join(t,`src/server/services/plunk.ts`)),await O.copy(E.join(d,`template/extras/emailProviders/plunk/email.tsx`),E.join(t,`src/server/auth/email.tsx`))}async function tt({project:e}){let t=c.projectDir;C({dependencies:[`resend`],devMode:!1,projectDir:t});let n;n=typeof c.apiKey==`string`?c.apiKey:a()?``:b(await v({message:`Enter your Resend API key\n${D.dim(`Only "Sending Access" permission required: https://resend.com/api-keys`)}`})),n||x.warn(`You will need to add your Resend API key to the .env file manually for your app to run.`),console.log(``),await Qe({projectDir:t,project:e,envs:[{name:`RESEND_API_KEY`,zodValue:`z.string().startsWith("re_")`,type:`server`,defaultValue:n}]}),await O.copy(E.join(d,`template/extras/emailProviders/resend/service.ts`),E.join(t,`src/server/services/resend.ts`)),await O.copy(E.join(d,`template/extras/emailProviders/resend/email.tsx`),E.join(t,`src/server/auth/email.tsx`))}const nt=async({noInstall:e,installServerFiles:t}={})=>{let n=ne();n.start(`Adding React Email`),await $e({noInstall:e,installServerFiles:t}),n.stop(`React Email added`)};async function rt(e){let t=c.projectDir,n=S();if(n.ui===`shadcn`||n.tanstackQuery)return!1;C({projectDir:t,dependencies:[`@tanstack/react-query`],devMode:!1}),C({projectDir:t,dependencies:[`@tanstack/react-query-devtools`],devMode:!0});let r=E.join(d,`template`,`extras`);c.appType===`browser`?(O.copySync(E.join(r,`config`,`get-query-client.ts`),E.join(t,`src/config/get-query-client.ts`)),O.copySync(E.join(r,`config`,`query-provider.tsx`),E.join(t,`src/config/query-provider.tsx`))):c.appType===`webviewer`&&O.copySync(E.join(r,`config`,`query-provider-vite.tsx`),E.join(t,`src/config/query-provider.tsx`));let i=e?.project??w(t),a=i.addSourceFileAtPath(E.join(t,c.appType===`browser`?`src/app/layout.tsx`:`src/main.tsx`));if(a.addImportDeclaration({moduleSpecifier:`@/config/query-provider`,defaultImport:`QueryProvider`}),c.appType===`browser`){let e=a.getFunction(e=>e.isDefaultExport())?.getBody()?.getFirstDescendantByKind(A.ReturnStatement)?.getDescendantsOfKind(A.JsxOpeningElement).find(e=>e.getTagNameNode().getText()===`body`)?.getParentIfKind(A.JsxElement),t=e?.getJsxChildren().map(e=>e.getText()).filter(Boolean).join(`
5
+ `);e?.getChildSyntaxList()?.replaceWithText(`<QueryProvider>
6
+ ${t}
7
+ </QueryProvider>`)}else if(c.appType===`webviewer`){let e=a.getDescendantsOfKind(A.JsxElement).find(e=>e.getOpeningElement().getTagNameNode().getText()===`MantineProvider`);e?.replaceWithText(`<QueryProvider>
8
+ ${e.getText()}
9
+ </QueryProvider>`)}return e?.project||await T(i),ce({...n,tanstackQuery:!0}),!0}const it=async()=>{let e=ne();e.start(`Adding Tanstack Query`),await rt(),e.stop(`Tanstack Query added`)};async function at(e){if(e===`webviewer`||e===`auth`)return e;if(a())throw Error("Addon target is required in non-interactive mode. Use `proofkit add addon webviewer`.");return b(await m({message:`Which add-on do you want to install locally?`,options:[{value:`webviewer`,label:`WebViewer`,hint:`ProofKit WebViewer add-on`},{value:`auth`,label:`Auth`,hint:`ProofKit Auth add-on`}]}))}async function ot(e){g({commandName:`add addon`});let t=S(),n=await at(e);if(n===`webviewer`&&t.appType!==`webviewer`)throw Error(`The WebViewer add-on can only be added from a WebViewer ProofKit project.`);if(n===`auth`&&t.appType!==`browser`)throw Error(`The auth add-on can only be added from a browser ProofKit project.`);await Ee({addonName:n===`webviewer`?`wv`:`auth`})}const st=()=>{let e=new Le(`addon`).description(`Install or update local FileMaker add-on files`).argument(`[target]`,`Add-on to install locally (webviewer or auth)`).addOption(oe).addOption(se).action(async e=>{await ot(e)});return e.hook(`preAction`,e=>{u(e.opts())}),e};function ct(e,t){e.addImportDeclaration({defaultImport:`UserMenu`,moduleSpecifier:t});let n=e.getImportDeclaration(e=>e.getModuleSpecifierValue()===`@mantine/core`);n?n.getNamedImports().find(e=>e.getName()===`Group`)||n.addNamedImport({name:`Group`}):e.addImportDeclaration({namedImports:[{name:`Group`}],moduleSpecifier:`@mantine/core`});let r=ge(e.getFunction(e=>e.isDefaultExport())?.getBody()?.getFirstDescendantByKind(A.ReturnStatement)),i=r?.getFirstDescendantByKind(A.JsxOpeningFragment)?.getParentIfKind(A.JsxFragment)?.getFirstDescendantByKind(A.SyntaxList)?.getText();if(!i){console.log(`Failed to inject into header slot at ${e.getFilePath()}`);return}r?.replaceWithText(`return (<><Group>${i}<UserMenu /></Group></>)`),r?.formatText(),e.saveSync()}const lt=async({projectDir:e})=>{C({projectDir:e,dependencies:[`@clerk/nextjs`,`@clerk/themes`],devMode:!1});let t=E.join(d,`template/extras`),n=E.join(e,`src/middleware.ts`);if(O.existsSync(n))console.log(D.yellow(`Middleware already exists. To require auth for your app, be sure to follow the guide to setup Clerk middleware. https://clerk.com/docs/references/nextjs/clerk-middleware#clerk-middleware-next-js`));else{let e=E.join(t,`src/middleware/clerk.ts`);O.copySync(e,n)}O.copySync(E.join(t,`src/app/clerk-auth`),E.join(e,`src/app/auth`)),O.copySync(E.join(t,`src/components/clerk-auth`),E.join(e,`src/components/clerk-auth`));let r=E.join(e,`src/app/layout.tsx`),i=w(e);ut(i.addSourceFileAtPath(r)),ct(i.addSourceFileAtPath(E.join(e,`src/components/AppShell/slot-header-right.tsx`)),`@/components/clerk-auth/user-menu`),ct(i.addSourceFileAtPath(E.join(e,`src/components/AppShell/slot-header-mobile-content.tsx`)),`@/components/clerk-auth/user-menu-mobile`),dt(i.addSourceFileAtPathIfExists(E.join(e,`src/server/safe-action.ts`))),await Qe({projectDir:e,project:i,envs:[{name:`NEXT_PUBLIC_CLERK_SIGN_IN_URL`,zodValue:`z.string()`,defaultValue:`/auth/signin`,type:`client`},{name:`NEXT_PUBLIC_CLERK_SIGN_UP_URL`,zodValue:`z.string()`,defaultValue:`/auth/signup`,type:`client`},{name:`CLERK_SECRET_KEY`,zodValue:`z.string().startsWith('sk_').min(1, {
10
+ message:
11
+ "No Clerk Secret Key found. Did you create your Clerk app and copy the environment variables to you .env file?",
12
+ })`,type:`server`},{name:`NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY`,zodValue:`z.string().startsWith('pk_').min(1, {
13
+ message:
14
+ "No Clerk Public Key found. Did you create your Clerk app and copy the environment variables to you .env file?",
15
+ })`,type:`client`}],envFileDescription:`Hosted auth with Clerk. Set up a new app at https://dashboard.clerk.com/apps/new to get these values.`}),await T(i)};function ut(e){e.addImportDeclaration({namedImports:[{name:`ClerkAuthProvider`}],moduleSpecifier:`@/components/clerk-auth/clerk-provider`});let t=e.getFunction(e=>e.isDefaultExport())?.getBody()?.getFirstDescendantByKind(A.ReturnStatement)?.getDescendantsOfKind(A.JsxOpeningElement).find(e=>e.getTagNameNode().getText()===`MantineProvider`)?.getParentIfKind(A.JsxElement),n=t?.getJsxChildren().map(e=>e.getText()).filter(Boolean).join(`
16
+ `);t?.getChildSyntaxList()?.replaceWithText(`<ClerkAuthProvider>
17
+ ${n}
18
+ </ClerkAuthProvider>`)}function dt(e){if(!e){console.log(D.yellow(`Failed to inject into safe-action-client. Did you move the safe-action.ts file?`));return}e.addImportDeclaration({namedImports:[{name:`auth`,alias:`getAuth`}],moduleSpecifier:`@clerk/nextjs/server`}),e.addStatements(e=>e.writeLine(`export const authedActionClient = actionClient.use(async ({ next, ctx }) => {
19
+ const auth = getAuth();
20
+ if (!auth.userId) {
21
+ throw new Error("Unauthorized");
22
+ }
23
+ return next({ ctx: { ...ctx, auth } });
24
+ });
25
+
26
+ `))}const ft=async()=>{let e=Ve(`Installing files for auth...`).start(),t=c.projectDir;C({projectDir:t,dependencies:[`@node-rs/argon2`,`@oslojs/binary`,`@oslojs/crypto`,`@oslojs/encoding`,`js-cookie`],devMode:!1}),C({projectDir:t,dependencies:[`@types/js-cookie`],devMode:!0}),await O.copy(E.join(d,`template/extras/fmaddon-auth`),E.join(t,`src`));let n=w(t);await rt({project:n}),ct(n.addSourceFileAtPath(E.join(t,`src/components/AppShell/slot-header-right.tsx`)),`@/components/auth/user-menu`),pt(n.addSourceFileAtPathIfExists(E.join(t,`src/server/safe-action.ts`))),await Se({config:{type:`fmdapi`,envNames:void 0,clientSuffix:`Layout`,layouts:[{layoutName:`proofkit_auth_sessions`,schemaName:`sessions`,strictNumbers:!0},{layoutName:`proofkit_auth_users`,schemaName:`users`,strictNumbers:!0},{layoutName:`proofkit_auth_email_verification`,schemaName:`emailVerification`,strictNumbers:!0},{layoutName:`proofkit_auth_password_reset`,schemaName:`passwordReset`,strictNumbers:!0}],clearOldFiles:!0,validator:!1,path:`./src/server/auth/db`},projectDir:t,runCodegen:!1}),await $e({project:n,installServerFiles:!0}),mt(n.addSourceFileAtPath(E.join(t,`src/app/(main)/layout.tsx`))),await T(n);let r=!1;for(;!r;)if(r=await ht(t,e),r)e.text=`Successfully detected all required layouts in your FileMaker file.`;else if(!b(await h({message:`I have followed the above instructions, continue installing`,initialValue:!0})))throw new p({message:`User aborted the operation`});await Ce(),e.succeed(`Auth installed successfully`)};function pt(e){if(!e){console.log(D.yellow(`Failed to inject into safe-action-client. Did you move the safe-action.ts file?`));return}e.addImportDeclaration({namedImports:[{name:`getCurrentSession`}],moduleSpecifier:`./auth/utils/session`}),e.addStatements(e=>e.writeLine(`export const authedActionClient = actionClient.use(async ({ next, ctx }) => {
27
+ const { session, user } = await getCurrentSession();
28
+ if (session === null) {
29
+ throw new Error("Unauthorized");
30
+ }
31
+
32
+ return next({ ctx: { ...ctx, session, user } });
33
+ });
34
+ `))}function mt(e){e.addImportDeclaration({defaultImport:`Protect`,moduleSpecifier:`@/components/auth/protect`});let t=e.getFunction(e=>e.isDefaultExport())?.getBody()?.getFirstDescendantByKind(A.ReturnStatement)?.getFirstDescendantByKind(A.JsxElement);t?.replaceWithText(`<Protect>
35
+ ${t?.getText()}
36
+ </Protect>`)}async function ht(e,t){let n=S(),r=n.dataSources.filter(e=>e.type===`fm`).find(e=>e.name===`filemaker`);if(!r)return!1;n.envFile&&Me.config({path:E.join(e,n.envFile)});let i=process.env[r.envNames.apiKey],a=process.env[r.envNames.database],o=process.env[r.envNames.server];if(!(i&&a&&o))return!1;let s=await Te({dataApiKey:i,fmFile:a,server:o});return[`proofkit_auth_sessions`,`proofkit_auth_users`,`proofkit_auth_email_verification`,`proofkit_auth_password_reset`].every(e=>s.some(t=>t===e))?!0:(t.warn(`Required layouts not found`),await we({addonName:`auth`}),!1)}async function gt({options:e,noInstall:t=!1,projectDir:n=process.cwd()}){let r=S();if(r.ui===`shadcn`)throw Error(`Shadcn projects should add auth using the template registry`);if(r.auth.type!==`none`)throw Error(`Auth already exists`);if(!r.dataSources.some(e=>e.type===`fm`)&&e.type===`fmaddon`)throw Error(`A FileMaker data source is required to use the FM Add-on Auth`);if(!r.dataSources.some(e=>e.type===`fm`)&&e.type===`better-auth`)throw Error(`A FileMaker data source is required to use the Better-Auth`);e.type===`clerk`?await _t({projectDir:n}):e.type===`fmaddon`&&await vt(),await yt(),t||await me({projectDir:n})}async function _t({projectDir:e=process.cwd()}){await lt({projectDir:e}),le({auth:{type:`clerk`}})}async function vt(){await ft(),le({auth:{type:`fmaddon`}})}async function yt(){let e=c.projectDir,t=await Ke(`src/app/(main)/**/actions.ts`,{cwd:e});for(let n of t){let t=E.join(e,n);Ae(t,ke(t,`utf-8`).replace(/actionClient/g,`authedActionClient`))}}async function bt(){let e=S();if(e.appType!==`browser`)return y(`Auth is not supported for your app type.`);if(e.ui===`shadcn`)return y(`Adding auth is not yet supported for shadcn-based projects.`);let t=c.authType??b(await m({message:`What auth provider do you want to use?`,options:[{value:`fmaddon`,label:`FM Add-on Auth`,hint:`Self-hosted auth with email/password`},{value:`clerk`,label:`Clerk`,hint:`Hosted auth service with many providers`}]})),n=l([`clerk`,`fmaddon`]).parse(t);if(c.authType=n,n===`fmaddon`){let e=c.emailProvider??(a()?`none`:void 0)??b(await m({message:`What email provider do you want to use?\n${D.dim(`Used to send email verification codes. If you skip this, the codes will be displayed here in your terminal.`)}`,options:[{label:`Resend`,value:`resend`,hint:`Great dev experience`},{label:`Plunk`,value:`plunk`,hint:`Cheapest for <20k emails/mo, self-hostable`},{label:`Other / I'll do it myself later`,value:`none`}]})),t=l([`plunk`,`resend`,`none`]).parse(e);c.emailProvider=t,await gt({options:{type:n,emailProvider:t===`none`?void 0:t}})}else await gt({options:{type:n}})}const xt=()=>{let e=new Le(`auth`).description(`Add authentication to your project`).option(`--authType <authType>`,`Type of auth provider to use`).option(`--emailProvider <emailProvider>`,`Email provider to use (only for FM Add-on Auth)`).option(`--apiKey <apiKey>`,`API key to use for the email provider (only for FM Add-on Auth)`).addOption(oe).addOption(se).action(async()=>{let e=S();if(e.ui===`shadcn`)throw Error(`Shadcn projects should add auth using the template registry`);if(e.auth.type!==`none`)throw Error(`Auth already exists`);await bt()});return e.hook(`preAction`,e=>{u(e.opts())}),e};async function St({url:e}){let t=qe.generate({length:18,charset:`alphanumeric`}),n=new URL(`/otto/wizard/${t}`,e.origin),r=n.toString();_.info(`${D.bold(`If the browser window didn't open automatically, please open the following link to login into your OttoFMS server:`)}\n\n${D.cyan(r)}`),Pe(n.toString()).catch(()=>{});let i=ne();i.start(`Waiting for you to log in using the link above`);let a=await new Promise(n=>{let r=setInterval(()=>{k.get(`${e.origin}/otto/api/cli/checkHash/${t}`,{headers:{"Accept-Encoding":`deflate`}}).then(i=>{n(i.data.response),clearTimeout(a),clearInterval(r),k.delete(`${e.origin}/otto/api/cli/checkHash/${t}`,{headers:{"Accept-Encoding":`deflate`}}).catch(()=>{})}).catch(()=>{})},500),a=setTimeout(()=>{clearInterval(r),i.stop(`Login timed out. No worries - it happens to the best of us.`)},18e4)});return i.stop(`Login complete.`),a}async function Ct({url:e,token:t}){return(await k.get(`${e.origin}/otto/fmi/admin/api/v2/databases`,{headers:{Authorization:`Bearer ${t}`}})).data.response.databases}async function wt({url:e,token:t}){return(await k.get(`${e.origin}/otto/api/api-key`,{headers:{Authorization:`Bearer ${t}`}})).data.response[`api-keys`]}async function Tt({url:e,filename:t}){for(_.info(`${D.cyan(`Creating a Data API Key`)}\nEnter FileMaker credentials for ${D.bold(t)}.\n${D.dim(`The account must have the fmrest extended privilege enabled.`)}`);;){let n=b(await v({message:`Enter the account name for ${D.bold(t)}`})),r=b(await re({message:`Enter the password for ${D.bold(n)}`}));try{return await Et({url:e,filename:t,username:n,password:r})}catch(t){if(t instanceof Ie){let n=t.response?.data&&`messages`in t.response.data?t.response.data.messages?.[0]?.text:void 0;_.error(`${D.red(`Error creating Data API key:`)} ${n??`Error code ${t.response?.status}`}
37
+ ${D.dim(t.response?.status===400&&`Common reasons this might happen:
38
+ - The provided credentials are incorrect.
39
+ - The account does not have the fmrest extended privilege enabled.
40
+
41
+ You may also want to try to create an API directly in the OttoFMS dashboard:
42
+ ${e.origin}/otto/app/api-keys`)}
43
+ `)}else _.error(`${D.red(`Error creating Data API key:`)} Unknown error`);if(!b(await h({message:`Do you want to try and enter credentials again?`})))throw Error(`User cancelled`)}}}async function Et({url:e,filename:t,username:n,password:r}){return{apiKey:(await k.post(`${e.origin}/otto/api/api-key/create-only`,{database:t,label:`For FM Web App`,user:n,pass:r})).data.response.key}}async function Dt({payload:e,url:a,token:o}){let c=s({response:s({started:r(),batchId:n(),subDeploymentIds:t(n())}),messages:t(s({code:n(),text:i()}))}),l=await k.post(`${a.origin}/otto/api/deployment`,e,{headers:{Authorization:`Bearer ${o}`}}).catch(e=>{throw console.error(e.response.data),e});return c.parse(l.data)}async function Ot({url:e,token:r,deploymentId:a}){let c=s({response:s({id:n(),status:l([`queued`,`running`,`scheduled`,`complete`,`aborted`,`unknown`]),running:o(),created_at:i(),started_at:i(),updated_at:i()}),messages:t(s({code:n(),text:i()}))}),u=await k.get(`${e.origin}/otto/api/deployment/${a}`,{headers:{Authorization:`Bearer ${r}`}});return c.parse(u.data)}const kt=process.env.FM_MCP_BASE_URL??`http://127.0.0.1:1365`;async function At(e){let t=new AbortController,n=setTimeout(()=>t.abort(),3e3);try{return await fetch(e,{signal:t.signal})}catch{return null}finally{clearTimeout(n)}}async function jt(e){let t=await At(e);return t?.ok?await t.json().catch(()=>null):null}async function Mt(e=kt){if(!(await At(`${e}/health`))?.ok)return{baseUrl:e,healthy:!1,connectedFiles:[]};let t=await jt(`${e}/connectedFiles`);return{baseUrl:e,healthy:!0,connectedFiles:Array.isArray(t)?t:[]}}const Nt=()=>{};function Pt(e,t,n){return new Proxy(Nt,{get(n,r){if(!(typeof r!=`string`||r===`then`))return Pt(e,[...t,r])},apply(n,r,i){let a=t[t.length-1],o={args:i,path:t};return a===`call`?o={args:i.length>=2?[i[1]]:[],path:t.slice(0,-1)}:a===`apply`&&(o={args:i.length>=2?i[1]:[],path:t.slice(0,-1)}),e(o)}})}const Ft=e=>Pt(e,[]);function It(e,...t){let n=Object.assign(Object.create(null),e);for(let e of t)for(let t in e){if(t in n&&n[t]!==e[t])throw Error(`Duplicate key ${t}`);n[t]=e[t]}return n}function Lt(e){return!!e&&!Array.isArray(e)&&typeof e==`object`}function Rt(e){return typeof e==`function`}function zt(e){return Object.assign(Object.create(null),e)}var Bt=class extends Error{};function Vt(e){if(e instanceof Error)return e;let t=typeof e;if(!(t===`undefined`||t===`function`||e===null)){if(t!==`object`)return Error(String(e));if(Lt(e)){let t=new Bt;for(let n in e)t[n]=e[n];return t}}}function Ht(e){if(e instanceof Ut||e instanceof Error&&e.name===`TRPCError`)return e;let t=new Ut({code:`INTERNAL_SERVER_ERROR`,cause:e});return e instanceof Error&&e.stack&&(t.stack=e.stack),t}var Ut=class extends Error{constructor(e){let t=Vt(e.cause),n=e.message??t?.message??e.code;super(n,{cause:t}),this.code=e.code,this.name=`TRPCError`,this.cause||=t}};function Wt(e){return`input`in e?e:{input:e,output:e}}const Gt={input:{serialize:e=>e,deserialize:e=>e},output:{serialize:e=>e,deserialize:e=>e}},Kt=({shape:e})=>e,qt=`middlewareMarker`;function Jt(){function e(t){return{_middlewares:t,unstable_pipe(n){let r=`_middlewares`in n?n._middlewares:[n];return e([...t,...r])}}}function t(t){return e([t])}return t}function Yt(e){let t=async function(t){let n,r=await t.getRawInput();try{n=await e(r)}catch(e){throw new Ut({code:`BAD_REQUEST`,cause:e})}let i=Lt(t.input)&&Lt(n)?{...t.input,...n}:n;return t.next({input:i})};return t._type=`input`,t}function Xt(e){let t=async function({next:t}){let n=await t();if(!n.ok)return n;try{let t=await e(n.data);return{...n,data:t}}catch(e){throw new Ut({message:`Output validation failed`,code:`INTERNAL_SERVER_ERROR`,cause:e})}};return t._type=`output`,t}function Zt(e){let t=e;if(typeof t==`function`)return t;if(typeof t.parseAsync==`function`)return t.parseAsync.bind(t);if(typeof t.parse==`function`)return t.parse.bind(t);if(typeof t.validateSync==`function`)return t.validateSync.bind(t);if(typeof t.create==`function`)return t.create.bind(t);if(typeof t.assert==`function`)return e=>(t.assert(e),e);throw Error(`Could not find a validator fn`)}function Qt(e,t){let{middlewares:n=[],inputs:r,meta:i,...a}=t;return $t({...It(e,a),inputs:[...e.inputs,...r??[]],middlewares:[...e.middlewares,...n],meta:e.meta&&i?{...e.meta,...i}:i??e.meta})}function $t(e={}){let t={procedure:!0,inputs:[],middlewares:[],...e};return{_def:t,input(e){let n=Zt(e);return Qt(t,{inputs:[e],middlewares:[Yt(n)]})},output(e){return Qt(t,{output:e,middlewares:[Xt(Zt(e))]})},meta(e){return Qt(t,{meta:e})},use(e){return Qt(t,{middlewares:`_middlewares`in e?e._middlewares:[e]})},unstable_concat(e){return Qt(t,e._def)},query(e){return en({...t,type:`query`},e)},mutation(e){return en({...t,type:`mutation`},e)},subscription(e){return en({...t,type:`subscription`},e)},experimental_caller(e){return Qt(t,{caller:e})}}}function en(e,t){let n=Qt(e,{resolver:t,middlewares:[async function(e){return{marker:qt,ok:!0,data:await t(e),ctx:e.ctx}}]}),r={...n._def,type:e.type,experimental_caller:!!n._def.caller,meta:n._def.meta,$types:null},i=tn(n._def),a=n._def.caller;if(!a)return i;let o=async(...e)=>await a({args:e,invoke:i,_def:r});return o._def=r,o}function tn(e){async function t(t){if(!t||!(`getRawInput`in t))throw Error(`This is a client-only function.
44
+ If you want to call this function on the server, see https://trpc.io/docs/v11/server/server-side-calls`);async function n(r={index:0,ctx:t.ctx}){try{let i=e.middlewares[r.index];return await i({ctx:r.ctx,type:t.type,path:t.path,getRawInput:r.getRawInput??t.getRawInput,meta:e.meta,input:r.input,next(e){let t=e;return n({index:r.index+1,ctx:t&&`ctx`in t?{...r.ctx,...t.ctx}:r.ctx,input:t&&`input`in t?t.input:r.input,getRawInput:t&&`getRawInput`in t?t.getRawInput:r.getRawInput})}})}catch(e){return{ok:!1,error:Ht(e),marker:qt}}}let r=await n();if(!r)throw new Ut({code:`INTERNAL_SERVER_ERROR`,message:"No result from middlewares - did you forget to `return next()`?"});if(!r.ok)throw r.error;return r.data}return t._def=e,t}const nn=typeof window>`u`||`Deno`in window||globalThis.process?.env?.NODE_ENV===`test`||!!globalThis.process?.env?.JEST_WORKER_ID||!!globalThis.process?.env?.VITEST_WORKER_ID;function rn(e){return e._def&&`router`in e._def}const an={_ctx:null,_errorShape:null,_meta:null,queries:{},mutations:{},subscriptions:{},errorFormatter:Kt,transformer:Gt},on=[`then`,`call`,`apply`];function sn(e){function t(t){let n=new Set(Object.keys(t).filter(e=>on.includes(e)));if(n.size>0)throw Error("Reserved words used in `router({})` call: "+Array.from(n).join(`, `));let r=zt({});function i(e,t=[]){let n=zt({});for(let[a,o]of Object.entries(e??{})){if(rn(o)){n[a]=i(o._def.record,[...t,a]);continue}if(!cn(o)){n[a]=i(o,[...t,a]);continue}let e=[...t,a].join(`.`);if(r[e])throw Error(`Duplicate key: ${e}`);r[e]=o,n[a]=o}return n}let a=i(t),o={_config:e,router:!0,procedures:r,...an,record:a};return{...a,_def:o,createCaller:ln()({_def:o})}}return t}function cn(e){return typeof e==`function`}function ln(){return function(e){let t=e._def;return function(e,n){return Ft(async({path:r,args:i})=>{let a=r.join(`.`);if(r.length===1&&r[0]===`_def`)return t;let o=t.procedures[a],s;try{return s=Rt(e)?await Promise.resolve(e()):e,await o({path:a,getRawInput:async()=>i[0],ctx:s,type:o._def.type})}catch(e){throw n?.onError?.({ctx:s,error:Ht(e),input:i[0],path:a,type:o._def.type}),e}})}}}function un(...e){let t=It({},...e.map(e=>e._def.record));return sn({errorFormatter:e.reduce((e,t)=>{if(t._def._config.errorFormatter&&t._def._config.errorFormatter!==Kt){if(e!==Kt&&e!==t._def._config.errorFormatter)throw Error(`You seem to have several error formatters`);return t._def._config.errorFormatter}return e},Kt),transformer:e.reduce((e,t)=>{if(t._def._config.transformer&&t._def._config.transformer!==Gt){if(e!==Gt&&e!==t._def._config.transformer)throw Error(`You seem to have several transformers`);return t._def._config.transformer}return e},Gt),isDev:e.every(e=>e._def._config.isDev),allowOutsideOfServer:e.every(e=>e._def._config.allowOutsideOfServer),isServer:e.every(e=>e._def._config.isServer),$types:e[0]?._def._config.$types})(t)}new class e{context(){return new e}meta(){return new e}create(e){let t={transformer:Wt(e?.transformer??Gt),isDev:e?.isDev??globalThis.process?.env.NODE_ENV!==`production`,allowOutsideOfServer:e?.allowOutsideOfServer??!1,errorFormatter:e?.errorFormatter??Kt,isServer:e?.isServer??nn,$types:null,experimental:e?.experimental??{}};if(!(e?.isServer??nn)&&e?.allowOutsideOfServer!==!0)throw Error(`You're trying to use @trpc/server in a non-server environment. This is not supported by default.`);return{_config:t,procedure:$t({meta:e?.defaultMeta}),middleware:Jt(),router:sn(t),mergeRouters:un,createCallerFactory:ln()}}};async function dn({url:e,ottoPort:t=3030}){return{fmsInfo:await pn(e),ottoInfo:await gn({url:e,ottoPort:t})}}const fn=e.object({data:e.object({APIVersion:e.number().optional(),AcceptEARPassword:e.boolean().optional(),AcceptEncrypted:e.boolean().optional(),AcceptUnencrypted:e.boolean().optional(),AdminLocalAuth:e.string().optional(),AllowChangeUploadDBFolder:e.boolean().optional(),AutoOpenForUpload:e.boolean().optional(),DenyGuestAndAutoLogin:e.string().optional(),Hostname:e.string().optional(),IsAppleInternal:e.boolean().optional(),IsETS:e.boolean().optional(),PremisesType:e.string().optional(),ProductVersion:e.string().optional(),PublicKey:e.string().optional(),RequiresDBPasswords:e.boolean().optional(),ServerID:e.string().optional(),ServerVersion:e.string()}),result:e.number()});async function pn(e){let t=new URL(e);t.pathname=`/fmws/serverinfo`;let n=await yn(t.toString()).then(e=>fn.safeParse(e.data));if(!n.success)throw console.error(`fmsInfoResult.error`,n.error.issues),new Ut({code:`BAD_REQUEST`,message:`Invalid FileMaker Server URL`});return n.data.data}const mn=e.object({Otto:e.object({version:e.string(),serverNickname:e.string().default(``),isLicenseValid:e.boolean().optional()}),migratorVersion:e.string().optional(),FileMakerServer:e.object({version:e.object({long:e.string(),short:e.string()}),running:e.boolean().optional()}),isMac:e.boolean().optional(),platform:e.string().optional(),host:e.string().optional()}),hn=e.object({response:mn});async function gn({url:e,ottoPort:t=3030}){let n=await _n(e);return n||=await vn(e,t),n}async function _n(e){try{let t=new URL(e);return t.pathname=`/otto/api/info`,await yn(t.toString()).then(e=>hn.parse(e.data).response)}catch{return console.log(`unable to fetch otto4 info, trying otto3`),null}}async function vn(e,t){try{let n=new URL(e);return n.port=t?t.toString():`3030`,n.pathname=`/api/otto/info`,await yn(n.toString()).then(e=>mn.parse(e.data))}catch(e){return e instanceof Error&&console.error(`otto3 fetch error`,e.message),null}}async function yn(e){let t=new Fe.Agent({rejectUnauthorized:!1});return await k.get(e,{validateStatus:null,headers:{Connection:`close`},httpsAgent:t,timeout:1e4})}const bn=e=>e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,xn=/^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,Sn=e=>{let t=bn(e),n=t.split(`/`),r=n.findIndex(e=>e.startsWith(`@`)),i=n.at(-1);if(n.findIndex(e=>e.startsWith(`@`))!==-1&&(i=n.slice(r).join(`/`)),!(t===`.`||xn.test(i??``)))return`Name must consist of only lowercase alphanumeric characters, '-', and '_'`},Cn=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/,wn=async e=>{let t=S(),n=c.projectDir,r=e?.sourceName;if(r)r=e?.sourceName;else if(t.dataSources.filter(e=>e.type===`fm`).length>1){let e=await m({message:`Which FileMaker data source do you want to add a layout to?`,options:t.dataSources.filter(e=>e.type===`fm`).map(e=>({label:e.name,value:e.name}))});ee(e)&&(y(),process.exit(0)),r=i().parse(e)}r||=`filemaker`;let a=t.dataSources.filter(e=>e.type===`fm`).find(e=>e.name===r);if(!a)throw Error(`FileMaker data source ${r} not found in your ProofKit config`);let o=ne();o.start(`Loading layouts from your FileMaker file...`),t.envFile&&Me.config({path:E.join(n,t.envFile)});let s=process.env[a.envNames.apiKey],u=process.env[a.envNames.database],d=process.env[a.envNames.server];s&&u&&d||(o.stop(`Failed to load layouts`),y(`Missing required environment variables. Please check your .env file.`),process.exit(1)),s.startsWith(`KEY_`)||s.startsWith(`dk_`)||(o.stop(`Failed to load layouts`),y(`Invalid API key format. API key must start with 'KEY_' or 'dk_'.`),process.exit(1));let f=await Te({dataApiKey:s,fmFile:u,server:d}),p=ye({projectDir:n,dataSourceName:r}),h=p.map(e=>e.layout).filter(Boolean),re=p.map(e=>e.schemaName).filter(Boolean);o.stop(`Loaded layouts from your FileMaker file`),h.length>0&&ie(h.join(`
45
+ `),`Detected existing layouts in your project`),h.push(`-`);let g=e?.layoutName;(g===``||!f.includes(g??``))&&(g=void 0);let _=g??b(await ae({message:`Select a new layout to read data from`,emptyMessage:`No matching layouts found.`,options:f.filter(e=>!h.includes(e)).map(e=>({label:e,value:e,keywords:[e]}))})),oe=En(_),se=e?.schemaName||b(await v({message:`Enter a friendly name for the new schema.\n${D.dim(`This will the name by which you refer to this layout in your codebase`)}`,defaultValue:oe,validate:e=>{if(e!==``){if(!Cn.test(e))return`Name must consist of only alphanumeric characters, '_', and must not start with a number`;if(re.includes(e))return`Schema name must be unique`}}})).toString(),x=e?.valueLists??await m({message:`Should we use value lists on this layout?\n${D.dim(`This will allow fields that contain a value list to be auto-completed in typescript and also validated to prevent incorrect values`)}`,options:[{label:`Yes, but allow empty fields`,value:`allowEmpty`,hint:`Empty fields or values that don't match the value list will be converted to an empty string`},{label:`Yes; empty values should fail validation`,value:`strict`,hint:`Empty fields or values that don't match the value list will cause validation to fail`},{label:`No, ignore value lists`,value:`ignore`,hint:`Fields will just be typed as strings`}]}),ce=l([`ignore`,`allowEmpty`,`strict`]).catch(`ignore`).parse(x);await ve({runCodegen:!0,projectDir:n,dataSourceName:r,schemas:[{layoutName:_,schemaName:se,valueLists:ce}]}),te(`Layout "${_}" added to your project as "${se}"`)},Tn=()=>new Le(`layout`).alias(`schema`).description(`Add a new layout to your fmschema file`).action(async e=>{let t=e.settings;await wn({settings:t})});function En(e){let t=e.replace(/[-\s]/g,`_`);for(let e of De)t.startsWith(e)&&(t=t.replace(e,``));return t}const Dn=`ProofKitDemo.fmp12`;async function On({url:e,token:t,operation:n}){let r={scheduled:!1,label:`Install ProofKit Demo`,deployments:[{name:`Install ProofKit Demo`,source:{type:`url`,url:`https://proofkit.dev/proofkit-demo/manifest.json`},fileOperations:[{target:{fileName:Dn},operation:n,source:{fileName:`ProofKitDemo.fmp12`},location:{folder:`default`,subFolder:``}}],concurrency:1,options:{closeFilesAfterBuild:!1,keepFilesClosedAfterComplete:!1,transferContainerData:!1}}],abortRemaining:!1},i=ne();i.start(`Deploying ProofKit Demo file...`);let{response:{subDeploymentIds:a}}=await Dt({payload:r,url:e,token:t}),o=a[0];if(!o)throw Error(`No deployment ID returned from the server`);for(;;){await new Promise(e=>setTimeout(e,2500));let{response:{status:n,running:r}}=await Ot({url:e,token:t,deploymentId:o});if(!r){if(n!==`complete`)throw Error(`Deployment didn't complete`);break}}let{apiKey:s}=await Et({filename:Dn,username:`admin`,password:`admin`,url:e});return i.stop(),{apiKey:s}}async function kn({projectDir:e,...t}){let n=S();if(n.appType===`webviewer`){let r=await Mt(),i=r.connectedFiles[0],o=t.name??`filemaker`;if(!t.server&&r.healthy&&i){C({projectDir:e,dependencies:[`@proofkit/fmdapi`],devMode:!1}),await _e({projectDir:e,connectedFileName:i,dataSourceName:o,baseUrl:r.baseUrl});let a={type:`fm`,name:o,envNames:o===`filemaker`?{database:`FM_DATABASE`,server:`FM_SERVER`,apiKey:`OTTO_API_KEY`}:{database:`${o.toUpperCase()}_FM_DATABASE`,server:`${o.toUpperCase()}_FM_SERVER`,apiKey:`${o.toUpperCase()}_OTTO_API_KEY`}};if(n.dataSources.push(a),ce(n),t.layoutName&&t.schemaName)await ve({projectDir:e,dataSourceName:o,schemas:[{layoutName:t.layoutName,schemaName:t.schemaName,valueLists:`allowEmpty`}]});else if(t.layoutName||t.schemaName)throw Error(`Both --layoutName and --schemaName must be provided together.`);else ie(`Detected local FM MCP at ${r.baseUrl} with connected file "${i}". Edit ${D.cyan(`proofkit-typegen.config.jsonc`)} to add layouts, then run ${D.cyan(`pnpm typegen`)} or ${D.cyan(`pnpm typegen:ui`)}.`,`Local FileMaker detected`);return}if(!t.server&&a())throw Error(`No local FM MCP connection was detected and no FileMaker server was provided. Start the local FM MCP proxy with a connected file or rerun with --server.`);if(!t.server&&b(await m({message:`Local FM MCP was not detected. Do you want to continue with hosted FileMaker server setup or skip for now?`,options:[{label:`Continue with hosted setup`,value:`hosted`},{label:`Skip for now`,value:`skip`}]}))===`skip`){ie(`You can come back later with ${D.cyan(`proofkit add data`)} after starting FM MCP locally or when you have a hosted server ready.`);return}}let r=n.dataSources.filter(e=>e.type===`fm`).map(e=>e.name),i=await An(t.server);if(!(i.ottoVersion&&i.ottoVersion.compare(new Ue(`4.7.0`))>0||t.adminApiKey))return y(`OttoFMS 4.7.0 or later is required to auto-login with this CLI. Please install/upgrade OttoFMS on your server, or pass an Admin API key with the --adminApiKey flag then try again`);let o=t.adminApiKey||(await St({url:i.url})).token,s=await Ct({url:i.url,token:o}),c=s.map(e=>e.filename.replace(`.fmp12`,``)).includes(Dn.replace(`.fmp12`,``)),l=t.fileName;for(;(l=t.fileName||b(await ae({message:`Which file would you like to connect to? ${D.dim(`(TIP: Select the file where your data is stored)`)}`,emptyMessage:`No matching files found.`,options:[{value:`$deployDemoFile`,label:`Deploy NEW ProofKit Demo File`,hint:`Use OttoFMS to deploy a new file for testing`,keywords:[`demo`,`proofkit`]},...s.sort((e,t)=>e.filename.localeCompare(t.filename)).map(e=>({value:e.filename,label:e.filename,hint:e.status,keywords:[e.filename]}))]})),l===`$deployDemoFile`)&&c&&!b(await h({message:`The demo file already exists, do you want to replace it with a fresh copy?`,initialValue:!1})););if(!l)throw Error(`No file selected`);let u=t.dataApiKey;if(l===`$deployDemoFile`){let{apiKey:e}=await On({url:i.url,token:o,operation:c?`replace`:`install`});u=e,l=Dn,t.layoutName=t.layoutName??`API_Contacts`,t.schemaName=t.schemaName??`Contacts`}else{let e=(await wt({url:i.url,token:o})).filter(e=>e.database===l);if(!u&&e.length>0){let t=b(await ae({message:`Which OttoFMS Data API key would you like to use? ${D.dim(`(This determines the access that you'll have to the data in this file)`)}`,emptyMessage:`No matching API keys found.`,options:[...e.map(e=>({value:e.key,label:`${D.bold(e.label)} - ${e.user}`,hint:`${e.key.slice(0,5)}...${e.key.slice(-4)}`,keywords:[e.label,e.user,e.database]})),{value:`create`,label:`Create a new API key`,hint:`Requires FileMaker credentials for this file`,keywords:[`create`,`new`]}]}));if(typeof t!=`string`)throw Error(`Invalid key`);t!==`create`&&(u=t)}u||=(await Tt({filename:l,url:i.url})).apiKey}if(!u)throw Error(`No API key`);let d=r.length===0?`filemaker`:t.name??b(await v({message:`What do you want to call this data source?`,validate:e=>e===`filemaker`?`That name is reserved`:r?.includes(e)?`That name is already in use in this project, pick something unique`:Sn(e)})),f={type:`fm`,name:d,envNames:d===`filemaker`?{database:`FM_DATABASE`,server:`FM_SERVER`,apiKey:`OTTO_API_KEY`}:{database:`${d.toUpperCase()}_FM_DATABASE`,server:`${d.toUpperCase()}_FM_SERVER`,apiKey:`${d.toUpperCase()}_OTTO_API_KEY`}},p=w(e),ee=await Qe({projectDir:e,project:p,envs:[{name:f.envNames.database,zodValue:`z.string().endsWith(".fmp12")`,defaultValue:l,type:`server`},{name:f.envNames.server,zodValue:`z.string().url()`,type:`server`,defaultValue:i.url.origin},{name:f.envNames.apiKey,zodValue:`z.string().startsWith("dk_") as z.ZodType<OttoAPIKey>`,type:`server`,defaultValue:u}]}),te=ee.getImportDeclaration(e=>e.getModuleSpecifierValue()===`@proofkit/fmdapi`);te?(te.getNamedImports().find(e=>e.getName()===`OttoAPIKey`)?.remove(),te.addNamedImport({name:`OttoAPIKey`,isTypeOnly:!0})):ee.addImportDeclaration({namedImports:[{name:`OttoAPIKey`,isTypeOnly:!0}],moduleSpecifier:`@proofkit/fmdapi`}),C({projectDir:e,dependencies:[`@proofkit/fmdapi`],devMode:!1}),n.dataSources.push(f),ce(n),be({dataSourceName:d,envNames:d===`filemaker`?void 0:f.envNames}),await T(p),await wn({settings:n,sourceName:d,projectDir:e,layoutName:t.layoutName,schemaName:t.schemaName,valueLists:`allowEmpty`})}async function An(e){let t=ne(),n=null,r=null,i=null,a=e;for(;r===null;){let e=a??b(await v({message:`What is the URL of your FileMaker Server?\n${D.cyan(`TIP: You can copy any valid path on the server and paste it here.`)}`,validate:e=>{try{let t=e;t.startsWith(`https://`)||(t=t.startsWith(`http://`)?t.replace(`http://`,`https://`):`https://${t}`),new URL(t);return}catch{return`Please enter a valid URL`}}}));try{n=new URL(e)}catch{_.error(`Invalid URL: ${e.toString()}`);continue}t.start(`Validating Server URL...`);let{fmsInfo:o,ottoInfo:s}=await dn({url:n.origin});t.stop();let c=o.ServerVersion.split(` `)[0];if(!c){_.error(`Unable to parse FileMaker Server version`),a=void 0;continue}r=new Ue(c),i=s?.Otto.version?new Ue(s.Otto.version):null,a=void 0}if(n===null)throw Error(`Unable to get FileMaker Server URL`);return ie(`🎉 FileMaker Server version ${r} detected \n
46
+ ${i?`🎉 OttoFMS version ${i} detected`:`❌ OttoFMS not detected`}`),{url:n,ottoVersion:i,fmsVersion:r}}const jn=l([`fm`,`supabase`]),Mn=async()=>{let e=jn.parse(await m({message:`Which data souce do you want to add?`,options:[{label:`FileMaker`,value:`fm`},{label:`Supabase`,value:`supabase`}]}));if(e===`supabase`)throw Error(`Not implemented`);if(e===`fm`)await kn({projectDir:process.cwd()});else throw Error(`Invalid data source`)},Nn=()=>{let e=new Le(`data`);return e.description(`Add a new data source to your project`),e.addOption(oe),e.hook(`preAction`,(e,t)=>{u(t.opts());let n=g({commandName:`add`});t.setOptionValue(`settings`,n)}),e},Pn=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,Fn=async({projectDir:e,pageDir:t,dataSource:n,schemaName:r})=>{if(!n)throw Error(`DataSource is required for table page`);if(!r)throw Error(`SchemaName is required for table page`);if(n.type!==`fm`)throw Error(`FileMaker DataSource is required for table page`);let i=he({projectDir:e,dataSourceName:n.name}),a=xe({schemaName:r,dataSourceName:n.name}),o=S();if(o.ui===`shadcn`)return;let s=o.auth,l={__SOURCE_NAME__:n.name,__TYPE_NAME__:`T${r}`,__ZOD_TYPE_NAME__:`Z${r}`,__CLIENT_NAME__:`${r}${i}`,__SCHEMA_NAME__:r,__ACTION_CLIENT__:s.type===`none`?`actionClient`:`authedActionClient`,__FIRST_FIELD_NAME__:a[0]??`NO_FIELDS_ON_YOUR_LAYOUT`},u=await O.readdir(t);for await(let e of u){let n=E.join(t,e),r=await O.readFile(n,`utf8`);for(let[e,t]of Object.entries(l))r=r.replace(new RegExp(e,`g`),t);await O.writeFile(n,r,`utf8`)}let d=w(e),f=d.addSourceFileAtPath(E.join(t,c.appType===`browser`?`table.tsx`:`index.tsx`)).getVariableDeclaration(`columns`)?.getInitializerIfKind(A.ArrayLiteralExpression),p=Rn(a.filter(Boolean));for await(let e of p)f?.addElement(t=>t.inlineBlock(()=>{In(e)?t.write(`accessorFn: (row) => row["${e}"],`):t.write(`accessorFn: (row) => row.${e},`),t.write(`header: "${e}",`)}).write(`,`).newLine());c.appType===`webviewer`&&await rt({project:d})&&await me(),await T(d)};function In(e){return!Pn.test(e)}const Ln=[`id`,`pk`,`createdat`,`updatedat`,`primarykey`,`createdby`,`modifiedby`,`creationtimestamp`,`modificationtimestamp`];function Rn(e){return e.filter(e=>!Ln.includes(e.toLowerCase())||e.startsWith(`_`))}const zn=async e=>{await Fn(e),await rt()&&await me()},Bn={blank:{requireData:!1,label:`Blank`,templatePath:`nextjs/blank`},table:{requireData:!0,label:`Basic Table`,hint:`Use to load and show multiple records`,templatePath:`nextjs/table`,postIntallFn:Fn},tableEdit:{requireData:!0,label:`Basic Table (editable)`,hint:`Use to load and show multiple records with inline edit functionality`,templatePath:`nextjs/table-edit`,postIntallFn:Fn},tableInfinite:{requireData:!0,label:`Infinite Table`,hint:`Automatically load more records when the user scrolls to the bottom`,templatePath:`nextjs/table-infinite`,postIntallFn:zn},tableInfiniteEdit:{requireData:!0,label:`Infinite Table (editable)`,hint:`Automatically load more records when the user scrolls to the bottom with inline edit functionality`,templatePath:`nextjs/table-infinite-edit`,postIntallFn:zn}},Vn={blank:{requireData:!1,label:`Blank`,templatePath:`vite-wv/blank`},table:{requireData:!0,label:`Basic Table`,hint:`Use to load and show multiple records`,templatePath:`vite-wv/table`,postIntallFn:Fn},tableEdit:{requireData:!0,label:`Basic Table (editable)`,hint:`Use to load and show multiple records with inline edit functionality`,templatePath:`vite-wv/table-edit`,postIntallFn:Fn}};async function Hn({projectDir:e,navType:t,...n}){let r=E.join(e,`src/app/navigation.tsx`);if(!O.existsSync(r))return;let i=w(e);i.addSourceFileAtPath(r).getVariableDeclaration(t===`primary`?`primaryRoutes`:`secondaryRoutes`)?.getInitializerIfKind(A.ArrayLiteralExpression)?.addElement(e=>e.block(()=>{e.write(`
47
+ label: "${n.label}",
48
+ type: "link",
49
+ href: "${n.href}",`)}).write(`,`)),await T(i)}const Un=async e=>{let t=c.projectDir,n=S();if(n.ui===`shadcn`)return y(`Adding pages is not yet supported for shadcn-based projects.`);let r=c.appType===`browser`?Object.entries(Bn):Object.entries(Vn);if(r.length===0)return y(`No templates found for your app type. Check back soon!`);let i=e?.routeName,o=n.replacedMainPage;if(c.appType===`webviewer`&&!o&&!a()&&!i){let e=b(await m({message:`Do you want to replace the default page?`,options:[{label:`Yes`,value:`yes`},{label:`No, maybe later`,value:`no`},{label:`No, don't ask again`,value:`never`}]}));(e===`never`||e===`yes`)&&(o=!0),e===`yes`&&(i=`/`)}i||=b(await v({message:`Enter the URL PATH for your new page`,validate:e=>{if(e.length===0)return`URL path is required`}})),i.startsWith(`/`)||(i=`/${i}`);let s=Re(i.replace(`/`,``).trim()),l=e?.template??b(await m({message:`What template should be used for this page?`,options:r.map(([e,t])=>({value:e,label:`${t.label}`,hint:t.hint}))})),u=r.find(([e])=>e===l)?.[1];if(!u)return y(`Page template ${l} not found`);let f,p;if(u.requireData){if(n.dataSources.length===0)return y(`This template requires a data source, but you don't have any. Add a data source first, or choose another page template`);let r=e?.dataSourceName??(n.dataSources.length>1?b(await m({message:`Which data source should be used for this page?`,options:n.dataSources.map(e=>({value:e.name,label:e.name}))})):n.dataSources[0]?.name);if(f=n.dataSources.find(e=>e.name===r),!f)return y(`Data source ${r} not found`);p=await Gn({projectDir:t,dataSource:f})}let ee=ne();ee.start(`Adding page from template`);let te=E.join(d,`template/pages`,u.templatePath),h=c.appType===`browser`?E.join(t,`src/app/(main)`,i):E.join(t,`src/routes`,i);await O.copy(te,h),c.appType===`browser`?s&&s!==``&&await Hn({projectDir:process.cwd(),navType:`primary`,label:s,href:i}):c.appType,await u.postIntallFn?.({projectDir:t,pageDir:h,dataSource:f,schemaName:p}),o!==n.replacedMainPage&&le({replacedMainPage:o}),ee.stop(`Added page!`);let re=fe();console.log(`\n${D.green(`Next steps:`)}\nTo preview this page, restart your dev server using the ${D.cyan(`${re===`npm`?`npm run`:re} dev`)} command\n`)},Wn=()=>{let e=new Le(`page`).description(`Add a new page to your project`).action(async()=>{await Un()});return e.addOption(oe),e.addOption(se),e.hook(`preAction`,()=>{u(e.opts()),c.baseCommand=`add`,g({commandName:`add`})}),e};async function Gn({projectDir:e=process.cwd(),dataSource:t}){if(t.type===`supabase`)throw Error(`Not implemented`);let n=ye({projectDir:e,dataSourceName:t.name}).map(e=>e.schemaName).filter(Boolean);if(n.length===0){y(`This data source doesn't have any schemas to load data from`);return}return n.length===1?n[0]:b(await m({message:`Which schema should this page load data from?`,options:n.map(e=>({label:e??``,value:e??``}))}))}var j;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(j||={});var Kn;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Kn||={});const M=j.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),N=e=>{switch(typeof e){case`undefined`:return M.undefined;case`string`:return M.string;case`number`:return Number.isNaN(e)?M.nan:M.number;case`boolean`:return M.boolean;case`function`:return M.function;case`bigint`:return M.bigint;case`symbol`:return M.symbol;case`object`:return Array.isArray(e)?M.array:e===null?M.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?M.promise:typeof Map<`u`&&e instanceof Map?M.map:typeof Set<`u`&&e instanceof Set?M.set:typeof Date<`u`&&e instanceof Date?M.date:M.object;default:return M.unknown}},P=j.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var F=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,j.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};F.create=e=>new F(e);const qn=(e,t)=>{let n;switch(e.code){case P.invalid_type:n=e.received===M.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,j.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:n=`Unrecognized key(s) in object: ${j.joinValues(e.keys,`, `)}`;break;case P.invalid_union:n=`Invalid input`;break;case P.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${j.joinValues(e.options)}`;break;case P.invalid_enum_value:n=`Invalid enum value. Expected ${j.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:n=`Invalid function arguments`;break;case P.invalid_return_type:n=`Invalid function return type`;break;case P.invalid_date:n=`Invalid date`;break;case P.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:j.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case P.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case P.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case P.custom:n=`Invalid input`;break;case P.invalid_intersection_types:n=`Intersection results could not be merged`;break;case P.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,j.assertNever(e)}return{message:n}};let Jn=qn;function Yn(){return Jn}const Xn=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function I(e,t){let n=Yn(),r=Xn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===qn?void 0:qn].filter(e=>!!e)});e.common.issues.push(r)}var L=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return R;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return R;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const R=Object.freeze({status:`aborted`}),Zn=e=>({status:`dirty`,value:e}),z=e=>({status:`valid`,value:e}),Qn=e=>e.status===`aborted`,$n=e=>e.status===`dirty`,er=e=>e.status===`valid`,tr=e=>typeof Promise<`u`&&e instanceof Promise;var B;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(B||={});var V=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const nr=(e,t)=>{if(er(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){return this._error||=new F(e.common.issues),this._error}}};function H(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var U=class{get description(){return this._def.description}_getType(e){return N(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new L,ctx:{common:e.parent.common,data:e.data,parsedType:N(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(tr(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)};return nr(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return er(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>er(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:N(e)},r=this._parse({data:e,path:n.path,parent:n});return nr(n,await(tr(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:P.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new q({schema:this,typeName:Y.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return J.create(this,this._def)}nullable(){return ti.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Rr.create(this)}promise(){return ei.create(this,this._def)}or(e){return Br.create([this,e],this._def)}and(e){return Ur.create(this,e,this._def)}transform(e){return new q({...H(this._def),schema:this,typeName:Y.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new ni({...H(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new ai({typeName:Y.ZodBranded,type:this,...H(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ri({...H(this._def),innerType:this,catchValue:t,typeName:Y.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return oi.create(this,e)}readonly(){return si.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const rr=/^c[^\s-]{8,}$/i,ir=/^[0-9a-z]+$/,ar=/^[0-9A-HJKMNP-TV-Z]{26}$/i,or=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,sr=/^[a-z0-9_-]{21}$/i,cr=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,lr=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ur=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let dr;const fr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pr=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,mr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,hr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,gr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vr=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,yr=RegExp(`^${vr}$`);function br(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function xr(e){return RegExp(`^${br(e)}$`)}function Sr(e){let t=`${vr}T${br(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Cr(e,t){return!!((t===`v4`||!t)&&fr.test(e)||(t===`v6`||!t)&&mr.test(e))}function wr(e,t){if(!cr.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Tr(e,t){return!!((t===`v4`||!t)&&pr.test(e)||(t===`v6`||!t)&&hr.test(e))}var Er=class e extends U{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.string,received:t.parsedType}),R}let t=new L,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:P.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:P.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?I(n,{code:P.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&I(n,{code:P.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)ur.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`email`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)dr||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),dr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`emoji`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)or.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`uuid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)sr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`nanoid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)rr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cuid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ir.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cuid2`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)ar.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`ulid`,code:P.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),I(n,{validation:`url`,code:P.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`regex`,code:P.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),I(n,{code:P.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),I(n,{code:P.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),I(n,{code:P.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Sr(r).test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:P.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?yr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:P.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?xr(r).test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:P.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?lr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`duration`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Cr(e.data,r.version)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`ip`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?wr(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`jwt`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Tr(e.data,r.version)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`cidr`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?gr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`base64`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?_r.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`base64url`,code:P.invalid_string,message:r.message}),t.dirty()):j.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:P.invalid_string,...B.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...B.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...B.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...B.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...B.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...B.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...B.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...B.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...B.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...B.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...B.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...B.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...B.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...B.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...B.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...B.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...B.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...B.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...B.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...B.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...B.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...B.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...B.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...B.errToObj(t)})}nonempty(e){return this.min(1,B.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Er.create=e=>new Er({checks:[],typeName:Y.ZodString,coerce:e?.coerce??!1,...H(e)});function Dr(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Or=class e extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.number,received:t.parsedType}),R}let t,n=new L;for(let r of this._def.checks)r.kind===`int`?j.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),I(t,{code:P.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:P.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:P.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Dr(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),I(t,{code:P.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),I(t,{code:P.not_finite,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,B.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,B.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,B.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,B.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:B.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:B.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:B.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:B.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:B.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:B.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:B.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&j.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Or.create=e=>new Or({checks:[],typeName:Y.ZodNumber,coerce:e?.coerce||!1,...H(e)});var kr=class e extends U{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let t,n=new L;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:P.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),I(t,{code:P.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),I(t,{code:P.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):j.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.bigint,received:t.parsedType}),R}gte(e,t){return this.setLimit(`min`,e,!0,B.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,B.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,B.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,B.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:B.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:B.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:B.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:B.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:B.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:B.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};kr.create=e=>new kr({checks:[],typeName:Y.ZodBigInt,coerce:e?.coerce??!1,...H(e)});var Ar=class extends U{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.boolean,received:t.parsedType}),R}return z(e.data)}};Ar.create=e=>new Ar({typeName:Y.ZodBoolean,coerce:e?.coerce||!1,...H(e)});var jr=class e extends U{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.date,received:t.parsedType}),R}if(Number.isNaN(e.data.getTime()))return I(this._getOrReturnCtx(e),{code:P.invalid_date}),R;let t=new L,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:P.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),I(n,{code:P.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):j.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:B.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:B.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};jr.create=e=>new jr({checks:[],coerce:e?.coerce||!1,typeName:Y.ZodDate,...H(e)});var Mr=class extends U{_parse(e){if(this._getType(e)!==M.symbol){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.symbol,received:t.parsedType}),R}return z(e.data)}};Mr.create=e=>new Mr({typeName:Y.ZodSymbol,...H(e)});var Nr=class extends U{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.undefined,received:t.parsedType}),R}return z(e.data)}};Nr.create=e=>new Nr({typeName:Y.ZodUndefined,...H(e)});var Pr=class extends U{_parse(e){if(this._getType(e)!==M.null){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.null,received:t.parsedType}),R}return z(e.data)}};Pr.create=e=>new Pr({typeName:Y.ZodNull,...H(e)});var Fr=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}};Fr.create=e=>new Fr({typeName:Y.ZodAny,...H(e)});var Ir=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}};Ir.create=e=>new Ir({typeName:Y.ZodUnknown,...H(e)});var W=class extends U{_parse(e){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.never,received:t.parsedType}),R}};W.create=e=>new W({typeName:Y.ZodNever,...H(e)});var Lr=class extends U{_parse(e){if(this._getType(e)!==M.undefined){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.void,received:t.parsedType}),R}return z(e.data)}};Lr.create=e=>new Lr({typeName:Y.ZodVoid,...H(e)});var Rr=class e extends U{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==M.array)return I(t,{code:P.invalid_type,expected:M.array,received:t.parsedType}),R;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(I(t,{code:e?P.too_big:P.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(I(t,{code:P.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(I(t,{code:P.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new V(t,e,t.path,n)))).then(e=>L.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new V(t,e,t.path,n)));return L.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:B.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:B.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:B.toString(n)}})}nonempty(e){return this.min(1,e)}};Rr.create=(e,t)=>new Rr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...H(t)});function zr(e){if(e instanceof G){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=J.create(zr(r))}return new G({...e._def,shape:()=>t})}else if(e instanceof Rr)return new Rr({...e._def,type:zr(e.element)});else if(e instanceof J)return J.create(zr(e.unwrap()));else if(e instanceof ti)return ti.create(zr(e.unwrap()));else if(e instanceof Wr)return Wr.create(e.items.map(e=>zr(e)));else return e}var G=class e extends U{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape();return this._cached={shape:e,keys:j.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==M.object){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.object,received:t.parsedType}),R}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof W&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new V(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof W){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(I(n,{code:P.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new V(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>L.mergeObjectSync(t,e)):L.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return B.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:B.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Y.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of j.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of j.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return zr(this)}partial(t){let n={};for(let e of j.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of j.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof J;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Zr(j.objectKeys(this.shape))}};G.create=(e,t)=>new G({shape:()=>e,unknownKeys:`strip`,catchall:W.create(),typeName:Y.ZodObject,...H(t)}),G.strictCreate=(e,t)=>new G({shape:()=>e,unknownKeys:`strict`,catchall:W.create(),typeName:Y.ZodObject,...H(t)}),G.lazycreate=(e,t)=>new G({shape:e,unknownKeys:`strip`,catchall:W.create(),typeName:Y.ZodObject,...H(t)});var Br=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new F(e.ctx.common.issues));return I(t,{code:P.invalid_union,unionErrors:n}),R}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new F(e));return I(t,{code:P.invalid_union,unionErrors:i}),R}}get options(){return this._def.options}};Br.create=(e,t)=>new Br({options:e,typeName:Y.ZodUnion,...H(t)});const K=e=>e instanceof Yr?K(e.schema):e instanceof q?K(e.innerType()):e instanceof Xr?[e.value]:e instanceof Qr?e.options:e instanceof $r?j.objectValues(e.enum):e instanceof ni?K(e._def.innerType):e instanceof Nr?[void 0]:e instanceof Pr?[null]:e instanceof J?[void 0,...K(e.unwrap())]:e instanceof ti?[null,...K(e.unwrap())]:e instanceof ai||e instanceof si?K(e.unwrap()):e instanceof ri?K(e._def.innerType):[];var Vr=class e extends U{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.object)return I(t,{code:P.invalid_type,expected:M.object,received:t.parsedType}),R;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(I(t,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),R)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=K(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Y.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...H(r)})}};function Hr(e,t){let n=N(e),r=N(t);if(e===t)return{valid:!0,data:e};if(n===M.object&&r===M.object){let n=j.objectKeys(t),r=j.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Hr(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===M.array&&r===M.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Hr(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===M.date&&r===M.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Ur=class extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(Qn(e)||Qn(r))return R;let i=Hr(e.value,r.value);return i.valid?(($n(e)||$n(r))&&t.dirty(),{status:t.value,value:i.data}):(I(n,{code:P.invalid_intersection_types}),R)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ur.create=(e,t,n)=>new Ur({left:e,right:t,typeName:Y.ZodIntersection,...H(n)});var Wr=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return I(n,{code:P.invalid_type,expected:M.array,received:n.parsedType}),R;if(n.data.length<this._def.items.length)return I(n,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),R;!this._def.rest&&n.data.length>this._def.items.length&&(I(n,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new V(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>L.mergeArray(t,e)):L.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Wr.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Wr({items:e,typeName:Y.ZodTuple,rest:null,...H(t)})};var Gr=class e extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return I(n,{code:P.invalid_type,expected:M.object,received:n.parsedType}),R;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new V(n,e,n.path,e)),value:a._parse(new V(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?L.mergeObjectAsync(t,r):L.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof U?new e({keyType:t,valueType:n,typeName:Y.ZodRecord,...H(r)}):new e({keyType:Er.create(),valueType:t,typeName:Y.ZodRecord,...H(n)})}},Kr=class extends U{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return I(n,{code:P.invalid_type,expected:M.map,received:n.parsedType}),R;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new V(n,e,n.path,[a,`key`])),value:i._parse(new V(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return R;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return R;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Kr.create=(e,t,n)=>new Kr({valueType:t,keyType:e,typeName:Y.ZodMap,...H(n)});var qr=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return I(n,{code:P.invalid_type,expected:M.set,received:n.parsedType}),R;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(I(n,{code:P.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(I(n,{code:P.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return R;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new V(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:B.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:B.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};qr.create=(e,t)=>new qr({valueType:e,minSize:null,maxSize:null,typeName:Y.ZodSet,...H(t)});var Jr=class e extends U{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==M.function)return I(t,{code:P.invalid_type,expected:M.function,received:t.parsedType}),R;function n(e,n){return Xn({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Yn(),qn].filter(e=>!!e),issueData:{code:P.invalid_arguments,argumentsError:n}})}function r(e,n){return Xn({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Yn(),qn].filter(e=>!!e),issueData:{code:P.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ei){let e=this;return z(async function(...t){let o=new F([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return z(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new F([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new F([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Wr.create(t).rest(Ir.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Wr.create([]).rest(Ir.create()),returns:n||Ir.create(),typeName:Y.ZodFunction,...H(r)})}},Yr=class extends U{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Yr.create=(e,t)=>new Yr({getter:e,typeName:Y.ZodLazy,...H(t)});var Xr=class extends U{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return I(t,{received:t.data,code:P.invalid_literal,expected:this._def.value}),R}return{status:`valid`,value:e.data}}get value(){return this._def.value}};Xr.create=(e,t)=>new Xr({value:e,typeName:Y.ZodLiteral,...H(t)});function Zr(e,t){return new Qr({values:e,typeName:Y.ZodEnum,...H(t)})}var Qr=class e extends U{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return I(t,{expected:j.joinValues(n),received:t.parsedType,code:P.invalid_type}),R}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return I(t,{received:t.data,code:P.invalid_enum_value,options:n}),R}return z(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};Qr.create=Zr;var $r=class extends U{_parse(e){let t=j.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let e=j.objectValues(t);return I(n,{expected:j.joinValues(e),received:n.parsedType,code:P.invalid_type}),R}if(this._cache||=new Set(j.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=j.objectValues(t);return I(n,{received:n.data,code:P.invalid_enum_value,options:e}),R}return z(e.data)}get enum(){return this._def.values}};$r.create=(e,t)=>new $r({values:e,typeName:Y.ZodNativeEnum,...H(t)});var ei=class extends U{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==M.promise&&t.common.async===!1?(I(t,{code:P.invalid_type,expected:M.promise,received:t.parsedType}),R):z((t.parsedType===M.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ei.create=(e,t)=>new ei({type:e,typeName:Y.ZodPromise,...H(t)});var q=class extends U{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Y.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{I(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return R;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?R:r.status===`dirty`||t.value===`dirty`?Zn(r.value):r});{if(t.value===`aborted`)return R;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?R:r.status===`dirty`||t.value===`dirty`?Zn(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?R:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?R:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!er(e))return R;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>er(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):R);j.assertNever(r)}};q.create=(e,t,n)=>new q({schema:e,typeName:Y.ZodEffects,effect:t,...H(n)}),q.createWithPreprocess=(e,t,n)=>new q({schema:t,effect:{type:`preprocess`,transform:e},typeName:Y.ZodEffects,...H(n)});var J=class extends U{_parse(e){return this._getType(e)===M.undefined?z(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};J.create=(e,t)=>new J({innerType:e,typeName:Y.ZodOptional,...H(t)});var ti=class extends U{_parse(e){return this._getType(e)===M.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ti.create=(e,t)=>new ti({innerType:e,typeName:Y.ZodNullable,...H(t)});var ni=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};ni.create=(e,t)=>new ni({innerType:e,typeName:Y.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...H(t)});var ri=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return tr(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new F(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new F(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ri.create=(e,t)=>new ri({innerType:e,typeName:Y.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...H(t)});var ii=class extends U{_parse(e){if(this._getType(e)!==M.nan){let t=this._getOrReturnCtx(e);return I(t,{code:P.invalid_type,expected:M.nan,received:t.parsedType}),R}return{status:`valid`,value:e.data}}};ii.create=e=>new ii({typeName:Y.ZodNaN,...H(e)});var ai=class extends U{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},oi=class e extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?R:e.status===`dirty`?(t.dirty(),Zn(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?R:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Y.ZodPipeline})}},si=class extends U{_parse(e){let t=this._def.innerType._parse(e),n=e=>(er(e)&&(e.value=Object.freeze(e.value)),e);return tr(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};si.create=(e,t)=>new si({innerType:e,typeName:Y.ZodReadonly,...H(t)}),G.lazycreate;var Y;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Y||={});const X=Er.create;Or.create,ii.create,kr.create;const ci=Ar.create;jr.create,Mr.create,Nr.create,Pr.create;const li=Fr.create;Ir.create,W.create,Lr.create;const Z=Rr.create,Q=G.create;G.strictCreate,Br.create;const ui=Vr.create;Ur.create,Wr.create;const $=Gr.create;Kr.create,qr.create,Jr.create,Yr.create;const di=Xr.create,fi=Qr.create;$r.create,ei.create,q.create,J.create,ti.create,q.createWithPreprocess,oi.create;const pi=fi([`registry:lib`,`registry:block`,`registry:component`,`registry:ui`,`registry:hook`,`registry:page`,`registry:file`,`registry:theme`,`registry:style`,`registry:item`,`registry:example`,`registry:internal`]).describe(`The type property is used to specify the type of your registry item. This is used to determine the type and target path of the item when resolved for a project.`);ui(`type`,[Q({path:X(),content:X().optional(),type:pi.extract([`registry:file`,`registry:page`]),target:X()}),Q({path:X(),content:X().optional(),type:pi.exclude([`registry:file`,`registry:page`]),target:X().optional()})]);const mi=Q({$schema:X().optional(),extends:X().optional(),title:X().optional(),author:X().optional(),description:X().optional(),dependencies:Z(X()).optional(),devDependencies:Z(X()).optional(),registryDependencies:Z(X()).optional(),tailwind:Q({config:Q({content:Z(X()).optional(),theme:$(X(),li()).optional(),plugins:Z(X()).optional()}).optional()}).optional(),cssVars:Q({theme:$(X(),X()).optional(),light:$(X(),X()).optional(),dark:$(X(),X()).optional()}).optional(),css:$(X(),li()).optional(),envVars:$(X(),X()).optional(),meta:$(X(),li()).optional(),categories:Z(X()).optional()}),hi=ui(`type`,[Q({sourceFileName:X(),destinationPath:X().optional(),type:pi.extract([`registry:file`,`registry:page`]),handlebars:ci().optional()}),Q({sourceFileName:X(),destinationPath:X().optional(),type:pi.exclude([`registry:file`,`registry:page`]),handlebars:ci().optional()})]),gi=(e,t)=>Q({action:di(e),data:t,_from:X().optional()}),_i=ui(`action`,[gi(`next-steps`,Q({message:X()})),gi(`package.json script`,Q({scriptName:X(),scriptCommand:X()})),gi(`env`,Q({envs:Q({name:X(),zodValue:X(),defaultValue:X().optional().describe("This value will be added to the .env file, unless `addToRuntimeEnv` is set to `false`."),type:fi([`server`,`client`]),addToRuntimeEnv:ci().optional().describe(`Whether to add the env to the runtime env.`)}).array()})),gi(`wrap provider`,Q({providerOpenTag:X().describe(`The opening tag to use for the provider. This is used to wrap the provider in the correct location.`),providerCloseTag:X().describe(`The closing tag to use for the provider.`),imports:Z(Q({moduleSpecifier:X().describe(`The module to import from (e.g., '@/config/query-provider')`),defaultImport:X().optional().describe(`The default import name (e.g., 'QueryProvider')`),namedImports:Z(X()).optional().describe(`Array of named imports (e.g., ['QueryProvider', 'useQuery'])`)})).describe(`Array of import configurations for the provider. Each import should have either defaultImport or namedImports.`),parentTag:Z(X()).optional().describe(`If set, the provider will attempt to go inside of the parent tag. The first found tag will be used as the parent. If not set or none of the tags are found, the provider will be wrapped at the very top level.`)}))]),vi=fi([`component`,`page`,`utility`,`hook`,`email`]),yi=fi([`next-pages`,`next-app`,`manual`]),bi=mi.extend({title:X(),description:X().optional(),category:vi,files:Z(hi),registryType:pi,postInstall:Z(_i).optional().describe(`Steps that should be run by the ProofKit CLI after shadcn CLI is done`),minimumProofKitVersion:X().describe(`The minimum version of ProofKit required to use this template`).optional(),allowedFrameworks:Z(yi).optional(),schemaRequired:ci().optional().describe(`Whether this template requires a database schema to be selected`)}),xi=Q({name:X(),title:X(),category:vi,description:X().optional()}).array(),Si=je(import.meta.url),Ci=E.dirname(Si);E.resolve(Ci,`../templates`);function wi(e){return e.replace(/^\/+|\/+$/g,``)}function Ti(e){return(e.registryDependencies??[]).filter(e=>e.startsWith(`{proofkit}/r/`)).map(e=>e.replace(`{proofkit}/r/`,``)).map(wi)}const Ei={"{{schema.schemaName}}":`__HB_SCHEMA_NAME__`,"{{schema.sourceName}}":`__HB_SOURCE_NAME__`,"{{schema.clientSuffix}}":`__HB_CLIENT_SUFFIX__`};function Di(e){let t=e;for(let[e,n]of Object.entries(Ei))t=t.replace(new RegExp(Oi(n),`g`),e);return t}function Oi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}async function ki(e,t){let n=[`shadcn@latest`,`add`,...Array.isArray(e)?e:[e]];try{await Ne(`pnpm`,[`dlx`,...n],{stdio:`inherit`,cwd:c.projectDir??process.cwd()})}catch(e){throw x.error(`Failed to run shadcn add: ${e}`),e}}function Ai(){let e;try{e=S().registryUrl??f}catch{e=f}return e.endsWith(`/`)?e.slice(0,-1):e}function ji(){let e=E.join(c.projectDir,`components.json`);return JSON.parse(Oe.readFileSync(e,`utf8`))}const Mi=Ye({"@get/meta/:name":{output:bi},"@get/":{output:xi}}),Ni=Je({baseURL:`${Ai()}/r`,schema:Mi});async function Pi(e){let t=await Ni(`@get/meta/:name`,{params:{name:e}});if(t.error){if(t.error.status===404)return null;throw Error(t.error.message)}return t.data}Xe.registerHelper(`eq`,(e,t)=>e===t),Xe.registerHelper(`findFirst`,function(e,t,n){if(!(e&&Array.isArray(e)))return n.inverse(this);for(let r of e)if(t===`fm`&&r.type===`fm`)return n.fn(r);return n.inverse(this)});const Fi=[`id`,`pk`,`createdat`,`updatedat`,`primarykey`,`createdby`,`modifiedby`,`creationtimestamp`,`modificationtimestamp`];function Ii(e){return e.filter(e=>!Fi.includes(e.toLowerCase())||e.startsWith(`_`))}function Li(e){let{dataSource:t,schemaName:n}=e,r=he({projectDir:c.projectDir??process.cwd(),dataSourceName:t.name}),i=xe({schemaName:n,dataSourceName:t.name}).filter(Boolean);return{sourceName:t.name,schemaName:n,clientSuffix:r,allFieldNames:i,fieldNames:Ii(i)}}function Ri(e){return{proofkit:S(),shadcn:ji(),schema:e?Li(e):{sourceName:`UnknownDataSource`,schemaName:`UnknownSchema`,clientSuffix:`UnknownClientSuffix`,allFieldNames:[`UnknownFieldName`],fieldNames:[`UnknownFieldName`]}}}async function zi(e,t){let n=Bi(e,t),r=await O.readFile(n,`utf8`);r=Di(r);let i=Xe.compile(r)(t);await O.writeFile(n,i)}function Bi(e,t){let n=e.sourceFileName;if(e.destinationPath)return e.destinationPath;let r=c.projectDir??process.cwd(),{shadcn:i}=t,a=`src/components/blocks`;i?.aliases?.components&&(a=i.aliases.components.startsWith(`@/`)?`${i.aliases.components.replace(`@/`,`src/`)}/blocks`:`src/${i.aliases.components}/blocks`);let o={"registry:lib":i?.aliases?.lib||i?.aliases?.utils,"registry:component":i?.aliases?.components,"registry:ui":i?.aliases?.ui||i?.aliases?.components,"registry:hook":i?.aliases?.hooks,"registry:file":`src`,"registry:page":`src/app`,"registry:block":a,"registry:theme":`src/theme`,"registry:style":`src/styles`}[e.type];if(o){if(o.startsWith(`@/`)){let e=o.replace(`@/`,`src/`);return E.join(r,e,n)}return o.startsWith(`/`)||o.includes(`src/`)?E.join(r,o,n):E.join(r,`src`,o,n)}switch(e.type){case`registry:lib`:return E.join(r,`src`,`lib`,n);case`registry:file`:return E.join(r,`src`,n);case`registry:page`:{let e=`routeName`in t?t.routeName:void 0;if(e){let t=e===`/`?``:e;return E.join(r,`src`,`app`,`(main)`,t,n)}return E.join(r,`src`,`app`,n)}case`registry:block`:return E.join(r,`src`,`components`,`blocks`,n);case`registry:component`:return E.join(r,`src`,`components`,n);case`registry:ui`:return E.join(r,`src`,`components`,n);case`registry:hook`:return E.join(r,`src`,`hooks`,n);case`registry:theme`:return E.join(r,`src`,`theme`,n);case`registry:style`:return E.join(r,`src`,`styles`,n);default:return n}}function Vi(e){let t=E.join(c.projectDir,`package.json`),n=JSON.parse(Oe.readFileSync(t,`utf8`));n.scripts[e.data.scriptName]=e.data.scriptCommand,Oe.writeFileSync(t,JSON.stringify(n,null,2))}async function Hi(e){let{parentTag:t,imports:n,providerCloseTag:r,providerOpenTag:i}=e.data;try{let e=c.projectDir,a=w(e),o=(e=>e.startsWith(`@/`)?e.replace(`@/`,`src/`):e.startsWith(`./`)?e.substring(2):e)(ji().aliases.components),s=E.join(e,o,`providers.tsx`),l=a.addSourceFileAtPath(s);for(let e of n){let t={moduleSpecifier:e.moduleSpecifier,kind:Ge.ImportDeclaration};e.defaultImport&&(t.defaultImport=e.defaultImport),e.namedImports&&e.namedImports.length>0&&(t.namedImports=e.namedImports),l.addImportDeclaration(t)}let u=l.getFunction(e=>e.isDefaultExport());if(!u){x.warn(`No default export function found in ${s}`);return}let d=u?.getBody()?.getFirstDescendantByKind(A.ReturnStatement);if(!d){x.warn(`No return statement found in default export function`);return}let f;if(t&&t.length>0){for(let e of t)if(f=d?.getDescendantsOfKind(A.JsxOpeningElement).find(t=>t.getTagNameNode().getText()===e)?.getParentIfKind(A.JsxElement),f)break}if(f){let e=`${i}
50
+ ${f?.getJsxChildren().map(e=>e.getText()).filter(Boolean).join(`
51
+ `)}
52
+ ${r}`;f.getChildSyntaxList()?.replaceWithText(e)}else{let e=d?.getExpression();if(e){let t=e.getKind()===A.ParenthesizedExpression,n;n=t?e.asKindOrThrow(A.ParenthesizedExpression).getExpression().getText():e.getText();let a=`return (
53
+ ${i}
54
+ ${n}
55
+ ${r}
56
+ );`;d?.replaceWithText(a)}else x.warn(`No return expression found to wrap`)}await T(a),x.success(`Successfully wrapped provider in ${s}`)}catch(e){throw x.error(`Failed to wrap provider: ${e}`),e}}async function Ui(e){e.action===`package.json script`?Vi(e):e.action===`wrap provider`?await Hi(e):e.action===`next-steps`?x.info(e.data.message):e.action===`env`?await Qe({envs:e.data.envs}):x.error(`Unknown post-install step: ${e}`)}async function Wi(){await O.pathExists(`proofkit.json`)||(ce(de),ue())}async function Gi(){let e=c.projectDir??process.cwd();if(!await O.pathExists(E.join(e,`components.json`)))throw Error("Shadcn is not installed. Please run `pnpm dlx shadcn@latest init` to install it.");await Wi()}async function Ki({projectDir:e=process.cwd(),dataSource:t}){if(t.type===`supabase`)throw Error(`Not implemented`);let n=ye({projectDir:e,dataSourceName:t.name}).map(e=>e.schemaName).filter(e=>!!e);if(n.length===0){y(`This data source doesn't have any schemas to load data from`);return}return n.length===1?n[0]:b(await m({message:`Which schema should this template use?`,options:n.map(e=>({label:e,value:e}))}))}async function qi(e){let t=Ve(`Validating template`).start();try{await Gi();let n=await Pi(e);if(!n){t.fail(`Template ${e} not found in the ProofKit registry`);return}if(n.minimumProofKitVersion&&He.gt(n.minimumProofKitVersion,pe())){x.error(`Template ${e} requires ProofKit version ${n.minimumProofKitVersion}, but you are using version ${pe()}`),t.fail(`Template is not compatible with your ProofKit version`);return}t.succeed();let r=Ti(n),i=S().registryTemplates,a,o,s,l;if(n.schemaRequired){let e=S();if(e.dataSources.length===0){t.fail(`This template requires a data source, but you don't have any. Add a data source first.`);return}let n=e.dataSources.length>1?b(await m({message:`Which data source should be used for this template?`,options:e.dataSources.map(e=>({value:e.name,label:e.name}))})):e.dataSources[0]?.name;if(a=e.dataSources.find(e=>e.name===n),!a){t.fail(`Data source ${n} not found`);return}if(o=await Ki({projectDir:c.projectDir,dataSource:a}),!o){t.fail(`Schema selection was cancelled`);return}}n.category===`page`&&(s=b(await v({message:`Enter the URL PATH for your new page`,validate:e=>{if(e.length===0)return`URL path is required`}})),s.startsWith(`/`)&&(s=s.slice(1)),l=Re(s.replace(`/`,``).trim()));let u=new URL(`${Ai()}/r/${e}`);n.category===`page`&&u.searchParams.set(`routeName`,`/(main)/${s??e}`),e===`fmdapi`&&!i.includes(`utils/t3-env`)&&n.registryDependencies?.find(e=>e.includes(`utils/t3-env`))===void 0&&(await qi(`utils/t3-env`),i=S().registryTemplates),await ki([u.toString()],n.title);let d=n.files.filter(e=>e.handlebars);if(d.length>0){let t={...a&&o?Ri({dataSource:a,schemaName:o}):Ri(),...s&&{routeName:s},...l&&{pageName:l}},n=d.map(t=>({...t,destinationPath:t.destinationPath?.replace(`__PATH__`,`/(main)/${s??e}`)}));for(let e of n)await zi(e,t)}if(n.category===`page`&&s&&l&&await Hn({projectDir:c.projectDir,navType:`primary`,label:l,href:`/${s}`}),n.postInstall)for(let e of n.postInstall)e._from&&i.includes(e._from)||await Ui(e);le({registryTemplates:Be([...i,e,...r])})}catch(e){t.fail(`Failed to fetch template metadata.`),x.error(e)}}async function Ji(){let{data:e,error:t}=await Ni(`@get/`);if(t)throw Error(`Failed to fetch items from registry: ${t.message}`);return e}const Yi=async e=>{let t=S(),n=Ve(`Loading available components...`).start(),r;try{r=await Ji()}catch(e){n.fail(`Failed to load registry components`),x.error(e);return}let i=r.filter(e=>!t.registryTemplates.includes(e.name)),a=ze(i,e=>e.category),o=Be(i.map(e=>e.category));n.succeed();let s=b(await m({message:`What do you want to add to your project?`,options:[...o.includes(`page`)?[{label:`Page`,value:`page`}]:[],...t.dataSources.length>0?[{label:`Schema`,value:`schema`,hint:`load data from a new table or layout from an existing data source`}]:[],{label:`Data Source`,value:`data`,hint:`to connect to a new database or FileMaker file`},...o.filter(e=>e!==`page`).map(e=>({label:Re(e),value:e}))]}));if(s===`schema`)await wn();else if(s===`data`)await Mn();else if(o.includes(s)){let e=a[s];await qi(b(await m({message:`Select a ${s} to add to your project`,options:e.map(e=>({label:e.title,hint:e.description,value:e.name}))})))}else x.error(`Could not find any available components in the category "${s}"`)},Xi=async(e,t)=>{if(e===`addon`)return await ot(t?.target);if(e===`tanstack-query`)return await it();if(e!==void 0)return await qi(e);let n;try{n=S()}catch{return await Gi(),await Yi(t)}if(n.ui===`shadcn`)return await Yi(t);g({commandName:`add`});let r=b(await m({message:`What do you want to add to your project?`,options:[{label:`Page`,value:`page`},...n.dataSources.length>0?[{label:`Schema`,value:`schema`,hint:`load data from a new table or layout from an existing data source`}]:[],{label:`React Email`,value:`react-email`},{label:`Data Source`,value:`data`,hint:`to connect to a new database or FileMaker file`},...n.auth.type===`none`&&n.appType===`browser`?[{label:`Auth`,value:`auth`}]:[]]}));r===`auth`?await bt():r===`data`?await Mn():r===`page`?await Un():r===`schema`?await wn():r===`react-email`&&await nt({noInstall:t?.noInstall})},Zi=()=>{let e=new Le(`add`).description(`Add a new component to your project`).argument(`[name]`,`Type of component to add`).addOption(oe).addOption(se).option(`--noInstall`,`Do not run your package manager install command`,!1).action(async(e,t)=>{await Xi(e,t)});return e.hook(`preAction`,(e,t)=>{u(t.opts()),c.baseCommand=`add`}),e.hook(`preSubcommand`,(e,t)=>{u(t.opts()),c.baseCommand=`add`}),e.addCommand(xt()),e.addCommand(st()),e.addCommand(Wn()),e.addCommand(Tn()),e.addCommand(Nn()),e};export{Zi as makeAddCommand,Xi as runAdd};
57
+ //# sourceMappingURL=add-h15IdCWp.js.map