@proofkit/cli 1.2.0-beta.1 → 2.0.0-beta.1
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.
- package/CHANGELOG.md +133 -0
- package/dist/add-CfoeMDFa.js +57 -0
- package/dist/add-CfoeMDFa.js.map +1 -0
- package/dist/addPackageDependency-BE76r_Gs.js +4 -0
- package/dist/addPackageDependency-BE76r_Gs.js.map +1 -0
- package/dist/consts-BZnOMxpW.js +10 -0
- package/dist/consts-BZnOMxpW.js.map +1 -0
- package/dist/deploy-ib8_w4Q8.js +34 -0
- package/dist/deploy-ib8_w4Q8.js.map +1 -0
- package/dist/fmdapi-LpkpfSZp.js +3 -0
- package/dist/fmdapi-LpkpfSZp.js.map +1 -0
- package/dist/getUserPkgManager-Cph_6l1P.js +2 -0
- package/dist/getUserPkgManager-Cph_6l1P.js.map +1 -0
- package/dist/globalOptions-DmUayYY3.js +2 -0
- package/dist/globalOptions-DmUayYY3.js.map +1 -0
- package/dist/index-dr0nV3hP.d.ts +365 -0
- package/dist/index-dr0nV3hP.d.ts.map +1 -0
- package/dist/index.js +11 -147
- package/dist/index.js.map +1 -0
- package/dist/logger-DCEXcH26.js +2 -0
- package/dist/logger-DCEXcH26.js.map +1 -0
- package/dist/parseSettings-DYvHU8yJ.js +2 -0
- package/dist/parseSettings-DYvHU8yJ.js.map +1 -0
- package/dist/remove-D-aGocFU.js +2 -0
- package/dist/remove-D-aGocFU.js.map +1 -0
- package/dist/state-CiURqLoM.js +41 -0
- package/dist/state-CiURqLoM.js.map +1 -0
- package/dist/typegen-CNWUG1wR.js +2 -0
- package/dist/typegen-CNWUG1wR.js.map +1 -0
- package/dist/update-CDaX7MZ5.js +7 -0
- package/dist/update-CDaX7MZ5.js.map +1 -0
- package/dist/utils-CQMjIwwz.js +3 -0
- package/dist/utils-CQMjIwwz.js.map +1 -0
- package/package.json +61 -53
- package/template/extras/emailTemplates/auth-code.tsx +7 -26
- package/template/extras/emailTemplates/generic.tsx +8 -31
- package/template/extras/fmaddon-auth/emails/auth-code.tsx +7 -26
- package/template/extras/src/app/api/auth/[...nextauth]/route.ts +1 -1
- package/template/extras/src/server/next-auth/base.ts +3 -3
- package/template/fm-addon/ProofKitWV/de.xml +517 -20
- package/template/fm-addon/ProofKitWV/en.xml +517 -20
- package/template/fm-addon/ProofKitWV/es.xml +517 -20
- package/template/fm-addon/ProofKitWV/fr.xml +517 -20
- package/template/fm-addon/ProofKitWV/icon.png +0 -0
- package/template/fm-addon/ProofKitWV/icon@2x.png +0 -0
- package/template/fm-addon/ProofKitWV/info.json +9 -6
- package/template/fm-addon/ProofKitWV/info_de.json +12 -5
- package/template/fm-addon/ProofKitWV/info_en.json +16 -5
- package/template/fm-addon/ProofKitWV/info_es.json +12 -5
- package/template/fm-addon/ProofKitWV/info_fr.json +12 -5
- package/template/fm-addon/ProofKitWV/info_it.json +12 -5
- package/template/fm-addon/ProofKitWV/info_ja.json +12 -5
- package/template/fm-addon/ProofKitWV/info_ko.json +12 -5
- package/template/fm-addon/ProofKitWV/info_nl.json +12 -5
- package/template/fm-addon/ProofKitWV/info_pt.json +12 -5
- package/template/fm-addon/ProofKitWV/info_sv.json +12 -5
- package/template/fm-addon/ProofKitWV/info_zh.json +12 -5
- package/template/fm-addon/ProofKitWV/it.xml +517 -20
- package/template/fm-addon/ProofKitWV/ja.xml +517 -20
- package/template/fm-addon/ProofKitWV/ko.xml +517 -20
- package/template/fm-addon/ProofKitWV/nl.xml +517 -20
- package/template/fm-addon/ProofKitWV/preview.png +0 -0
- package/template/fm-addon/ProofKitWV/pt.xml +517 -20
- package/template/fm-addon/ProofKitWV/records_de.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_en.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_es.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_fr.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_it.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_ja.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_ko.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_nl.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_pt.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_sv.xml +0 -0
- package/template/fm-addon/ProofKitWV/records_zh.xml +0 -0
- package/template/fm-addon/ProofKitWV/sv.xml +517 -20
- package/template/fm-addon/ProofKitWV/template.xml +0 -0
- package/template/fm-addon/ProofKitWV/zh.xml +517 -20
- package/template/nextjs-mantine/AGENTS.md +1 -0
- package/template/nextjs-mantine/package.json +4 -4
- package/template/nextjs-shadcn/AGENTS.md +1 -0
- package/template/nextjs-shadcn/biome.json +18 -13
- package/template/nextjs-shadcn/package.json +11 -9
- package/template/nextjs-shadcn/src/app/layout.tsx +11 -11
- package/template/nextjs-shadcn/src/components/mode-toggle.tsx +39 -0
- package/template/nextjs-shadcn/src/components/ui/button.tsx +61 -0
- package/template/nextjs-shadcn/src/components/ui/dropdown-menu.tsx +267 -0
- package/template/nextjs-shadcn/src/components/ui/sonner.tsx +31 -0
- package/template/nextjs-shadcn/src/lib/env.ts +1 -1
- package/template/pages/nextjs/table-infinite/actions.ts +1 -1
- package/template/pages/nextjs/table-infinite-edit/actions.ts +1 -1
- package/template/vite-wv/.claude/launch.json +18 -0
- package/template/vite-wv/AGENTS.md +1 -0
- package/template/vite-wv/_gitignore +1 -0
- package/template/vite-wv/components.json +6 -6
- package/template/vite-wv/index.html +2 -2
- package/template/vite-wv/package.json +21 -35
- package/template/vite-wv/proofkit-typegen.config.jsonc +18 -0
- package/template/vite-wv/proofkit.json +4 -1
- package/template/vite-wv/scripts/filemaker.js +96 -0
- package/template/vite-wv/scripts/launch-fm.js +19 -0
- package/template/vite-wv/scripts/upload.js +17 -14
- package/template/vite-wv/src/App.tsx +84 -0
- package/template/vite-wv/src/index.css +96 -0
- package/template/vite-wv/src/lib/utils.ts +6 -0
- package/template/vite-wv/src/main.tsx +14 -35
- package/template/vite-wv/src/router.tsx +57 -0
- package/template/vite-wv/src/routes/query-demo.tsx +37 -0
- package/template/vite-wv/tsconfig.json +3 -1
- package/template/vite-wv/vite.config.ts +5 -5
- package/dist/external-DCpQkgKf.js +0 -1
- package/template/extras/config/_eslint.js +0 -27
- package/template/extras/config/_prettier.config.js +0 -6
- package/template/nextjs-mantine/.prettierrc +0 -3
- package/template/nextjs-shadcn/.prettierrc +0 -3
- package/template/nextjs-shadcn/next-env.d.ts +0 -6
- package/template/vite-wv/.prettierrc +0 -3
- package/template/vite-wv/pnpm-lock.yaml +0 -2294
- package/template/vite-wv/postcss.config.cjs +0 -15
- package/template/vite-wv/scripts/launch-fm.sh +0 -3
- package/template/vite-wv/src/components/AppLogo.tsx +0 -5
- package/template/vite-wv/src/components/full-screen-loader.tsx +0 -9
- package/template/vite-wv/src/config/env.ts +0 -16
- package/template/vite-wv/src/config/theme/globals.css +0 -125
- package/template/vite-wv/src/config/theme/mantine-theme.ts +0 -22
- package/template/vite-wv/src/routeTree.gen.ts +0 -111
- package/template/vite-wv/src/routes/__root.tsx +0 -21
- package/template/vite-wv/src/routes/index.tsx +0 -63
- package/template/vite-wv/src/routes/secondary.tsx +0 -28
- package/template/vite-wv/src/utils/notification-helpers.ts +0 -32
- package/template/vite-wv/src/utils/styles.ts +0 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,138 @@
|
|
|
1
1
|
# @proofgeist/kit
|
|
2
2
|
|
|
3
|
+
## 2.0.0-beta.1
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- d3c7979: Rewrite the CLI package for better observability, composability, and error tracing.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- d7f86a4: Update newly scaffolded apps to use Ultracite for linting and formatting by default, including the generated `lint` and `format` scripts and CLI formatting flow.
|
|
12
|
+
- @proofkit/typegen@1.1.0-beta.18
|
|
13
|
+
|
|
14
|
+
## 2.0.0-beta.22
|
|
15
|
+
|
|
16
|
+
### Minor Changes
|
|
17
|
+
|
|
18
|
+
- 5544f68: - cli: Revamp the WebViewer Vite template and harden `proofkit init` (ignore hidden files, improve non-interactive prompts, stop generating Cursor rules).
|
|
19
|
+
- cli: Install typegen skills locally when scaffolding projects.
|
|
20
|
+
- typegen: Add optional `fmHttp` config for using an FM HTTP proxy during metadata fetching.
|
|
21
|
+
- fmdapi/fmodata/webviewer: Add initial Codex skills for client and integration workflows.
|
|
22
|
+
|
|
23
|
+
### Patch Changes
|
|
24
|
+
|
|
25
|
+
- Updated dependencies [5544f68]
|
|
26
|
+
- Updated dependencies [f3980b1]
|
|
27
|
+
- Updated dependencies [8ca7a1e]
|
|
28
|
+
- Updated dependencies [1d4b69d]
|
|
29
|
+
- @proofkit/typegen@1.1.0-beta.17
|
|
30
|
+
- @proofkit/fmdapi@5.1.0-beta.2
|
|
31
|
+
|
|
32
|
+
## 2.0.0-beta.21
|
|
33
|
+
|
|
34
|
+
### Patch Changes
|
|
35
|
+
|
|
36
|
+
- Updated dependencies [2df365d]
|
|
37
|
+
- @proofkit/typegen@1.1.0-beta.16
|
|
38
|
+
|
|
39
|
+
## 2.0.0-beta.20
|
|
40
|
+
|
|
41
|
+
### Patch Changes
|
|
42
|
+
|
|
43
|
+
- @proofkit/typegen@1.1.0-beta.15
|
|
44
|
+
|
|
45
|
+
## 2.0.0-beta.19
|
|
46
|
+
|
|
47
|
+
### Patch Changes
|
|
48
|
+
|
|
49
|
+
- Updated dependencies [4e048d1]
|
|
50
|
+
- @proofkit/typegen@1.1.0-beta.14
|
|
51
|
+
|
|
52
|
+
## 2.0.0-beta.18
|
|
53
|
+
|
|
54
|
+
### Patch Changes
|
|
55
|
+
|
|
56
|
+
- Updated dependencies [4928637]
|
|
57
|
+
- @proofkit/typegen@1.1.0-beta.13
|
|
58
|
+
|
|
59
|
+
## 2.0.0-beta.17
|
|
60
|
+
|
|
61
|
+
### Patch Changes
|
|
62
|
+
|
|
63
|
+
- @proofkit/typegen@1.1.0-beta.12
|
|
64
|
+
|
|
65
|
+
## 2.0.0-beta.16
|
|
66
|
+
|
|
67
|
+
### Patch Changes
|
|
68
|
+
|
|
69
|
+
- @proofkit/typegen@1.1.0-beta.11
|
|
70
|
+
|
|
71
|
+
## 2.0.0-beta.15
|
|
72
|
+
|
|
73
|
+
### Patch Changes
|
|
74
|
+
|
|
75
|
+
- @proofkit/typegen@1.1.0-beta.10
|
|
76
|
+
|
|
77
|
+
## 2.0.0-beta.14
|
|
78
|
+
|
|
79
|
+
### Patch Changes
|
|
80
|
+
|
|
81
|
+
- Updated dependencies [eb7d751]
|
|
82
|
+
- @proofkit/typegen@1.1.0-beta.9
|
|
83
|
+
|
|
84
|
+
## 2.0.0-beta.13
|
|
85
|
+
|
|
86
|
+
### Patch Changes
|
|
87
|
+
|
|
88
|
+
- @proofkit/typegen@1.1.0-beta.8
|
|
89
|
+
|
|
90
|
+
## 2.0.0-beta.12
|
|
91
|
+
|
|
92
|
+
### Patch Changes
|
|
93
|
+
|
|
94
|
+
- Updated dependencies [3b55d14]
|
|
95
|
+
- @proofkit/typegen@1.1.0-beta.7
|
|
96
|
+
|
|
97
|
+
## 2.0.0-beta.11
|
|
98
|
+
|
|
99
|
+
### Patch Changes
|
|
100
|
+
|
|
101
|
+
- Updated dependencies
|
|
102
|
+
- @proofkit/typegen@1.1.0-beta.6
|
|
103
|
+
|
|
104
|
+
## 2.0.0-beta.10
|
|
105
|
+
|
|
106
|
+
### Patch Changes
|
|
107
|
+
|
|
108
|
+
- Updated dependencies [ae07372]
|
|
109
|
+
- Updated dependencies [23639ec]
|
|
110
|
+
- Updated dependencies [dfe52a7]
|
|
111
|
+
- @proofkit/typegen@1.1.0-beta.5
|
|
112
|
+
|
|
113
|
+
## 2.0.0-beta.9
|
|
114
|
+
|
|
115
|
+
### Patch Changes
|
|
116
|
+
|
|
117
|
+
- 863e1e8: Update tooling to Biome
|
|
118
|
+
- Updated dependencies [7dbfd63]
|
|
119
|
+
- Updated dependencies [863e1e8]
|
|
120
|
+
- @proofkit/typegen@1.1.0-beta.4
|
|
121
|
+
- @proofkit/fmdapi@5.0.3-beta.1
|
|
122
|
+
|
|
123
|
+
## 2.0.0-beta.8
|
|
124
|
+
|
|
125
|
+
### Patch Changes
|
|
126
|
+
|
|
127
|
+
- @proofkit/typegen@1.1.0-beta.3
|
|
128
|
+
|
|
129
|
+
## 2.0.0-beta.4
|
|
130
|
+
|
|
131
|
+
### Patch Changes
|
|
132
|
+
|
|
133
|
+
- Updated dependencies [4d9d0e9]
|
|
134
|
+
- @proofkit/typegen@1.0.11-beta.1
|
|
135
|
+
|
|
3
136
|
## 1.1.8
|
|
4
137
|
|
|
5
138
|
### Patch 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-CiURqLoM.js";import{i as d,r as f}from"./consts-BZnOMxpW.js";import{a as p,c as m,d as ee,f as h,i as g,l as te,m as _,n as v,o as ne,p as y,r as re,s as ie,t as ae,u as oe}from"./utils-CQMjIwwz.js";import{n as se,r as ce,t as le}from"./globalOptions-DmUayYY3.js";import{t as b}from"./logger-DCEXcH26.js";import{a as ue,n as x,o as de,r as fe,t as pe}from"./parseSettings-DYvHU8yJ.js";import{t as me}from"./getUserPkgManager-Cph_6l1P.js";import{n as he,r as ge,t as S}from"./addPackageDependency-BE76r_Gs.js";import{a as _e,d as ve,f as C,i as ye,n as be,o as xe,p as w,r as Se,s as Ce,t as we,u as Te}from"./fmdapi-LpkpfSZp.js";import Ee,{readFileSync as De,writeFileSync as Oe}from"node:fs";import T from"node:path";import{fileURLToPath as ke}from"node:url";import E from"chalk";import{execa as Ae}from"execa";import D from"fs-extra";import je from"open";import Me from"node:https";import O,{AxiosError as Ne}from"axios";import{Command as Pe}from"commander";import{capitalize as Fe,groupBy as Ie,uniq as Le}from"es-toolkit";import Re from"ora";import ze,{SemVer as Be}from"semver";import{execSync as Ve}from"node:child_process";import{StructureKind as He,SyntaxKind as k}from"ts-morph";import{glob as Ue}from"glob";import We from"dotenv";import Ge,{OttoAdapter as Ke}from"@proofkit/fmdapi";import qe from"node:os";import Je from"randomstring";import"jiti";import"fast-glob";import{createFetch as Ye,createSchema as Xe}from"@better-fetch/fetch";import Ze from"handlebars";function Qe(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=T.join(c.projectDir,e);if(D.existsSync(t))return t}if(e===!1)return null;throw b.warn(`Could not find T3 env files. Run "proofkit add utils/t3-env" to initialize them.`),Error(`T3 env file not found`)}async function $e({projectDir:e=c.projectDir,envs:t,envFileDescription:n,...r}){let i=Qe(),a=r.project??C(e),o=a.addSourceFileAtPath(i);if(!o)throw Error(`Schema file not found`);let s=o.getDescendantsOfKind(k.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(k.PropertyAssignment).find(e=>e.getName()===`server`)?.getFirstDescendantByKind(k.ObjectLiteralExpression),d=l.getDescendantsOfKind(k.PropertyAssignment).find(e=>e.getName()===`client`)?.getFirstDescendantByKind(k.ObjectLiteralExpression),f=l.getDescendantsOfKind(k.PropertyAssignment).find(e=>e.getName()===`experimental__runtimeEnv`)?.getFirstDescendantByKind(k.ObjectLiteralExpression),p=t.filter(e=>e.type===`server`),m=t.filter(e=>e.type===`client`);for(let e of p)u?.addPropertyAssignment({name:e.name,initializer:e.zodValue});for(let e of m)d?.addPropertyAssignment({name:e.name,initializer:e.zodValue}),f?.addPropertyAssignment({name:e.name,initializer:`process.env.${e.name}`});let ee=t.filter(e=>e.addToRuntimeEnv??!0).map(e=>`${e.name}=${e.defaultValue??``}`).join(`
|
|
2
|
+
`),h=T.join(e,`.env`);if(D.existsSync(h)){let t=D.readFileSync(h,`utf-8`),r=T.join(e,`.gitignore`);try{let t=``;D.existsSync(r)&&(t=D.readFileSync(r,`utf-8`)),t.includes(`.env`)||Ve(`echo ".env" >> "${r}"`,{cwd:e})}catch{}let i=`${t}
|
|
3
|
+
${n?`# ${n}\n${ee}`:ee}
|
|
4
|
+
`;D.writeFileSync(h,i)}return r.project||await w(a),o}async function et({...e}){let t=c.projectDir,n=x();if(n.ui===`shadcn`||n.reactEmail)return!1;D.ensureDirSync(T.join(t,`src/emails`)),S({dependencies:[`@react-email/components`,`@react-email/render`],devMode:!1,projectDir:t}),S({dependencies:[`react-email`,`@react-email/preview-server`],devMode:!0,projectDir:t});let r=D.readJSONSync(T.join(t,`package.json`));r.scripts||={},r.scripts[`email:preview`]=`email dev --port 3010 --dir=src/emails`,D.writeJSONSync(T.join(t,`package.json`),r,{spaces:2});let i=e.project??C(t);if(e.installServerFiles){let e=c.emailProvider;e===`plunk`?await tt({project:i}):e===`resend`?await nt({project:i}):await D.copy(T.join(d,`template/extras/emailProviders/none/email.tsx`),T.join(t,`src/server/auth/email.tsx`))}return await D.copy(T.join(d,`template/extras/emailTemplates/generic.tsx`),T.join(t,`src/emails/generic.tsx`)),e.installServerFiles&&await D.copy(T.join(d,`template/extras/emailTemplates/auth-code.tsx`),T.join(t,`src/emails/auth-code.tsx`)),e.project||await w(i),ue({...n,reactEmail:!0,reactEmailServer:!!e.installServerFiles||n.reactEmailServer}),e.noInstall||await ge({projectDir:t}),!0}async function tt({project:e}){let t=c.projectDir;S({dependencies:[`@plunk/node`],devMode:!1,projectDir:t});let n;n=typeof c.apiKey==`string`?c.apiKey:a()?``:v(await _({message:`Enter your Plunk API key\n${E.dim(`Enter your Secret API Key from https://app.useplunk.com/settings/api`)}`})),n||b.warn(`You will need to add your Plunk API key to the .env file manually for your app to run.`),console.log(``),await $e({projectDir:t,project:e,envs:[{name:`PLUNK_API_KEY`,zodValue:`z.string().startsWith("sk_")`,type:`server`,defaultValue:n}]}),await D.copy(T.join(d,`template/extras/emailProviders/plunk/service.ts`),T.join(t,`src/server/services/plunk.ts`)),await D.copy(T.join(d,`template/extras/emailProviders/plunk/email.tsx`),T.join(t,`src/server/auth/email.tsx`))}async function nt({project:e}){let t=c.projectDir;S({dependencies:[`resend`],devMode:!1,projectDir:t});let n;n=typeof c.apiKey==`string`?c.apiKey:a()?``:v(await _({message:`Enter your Resend API key\n${E.dim(`Only "Sending Access" permission required: https://resend.com/api-keys`)}`})),n||b.warn(`You will need to add your Resend API key to the .env file manually for your app to run.`),console.log(``),await $e({projectDir:t,project:e,envs:[{name:`RESEND_API_KEY`,zodValue:`z.string().startsWith("re_")`,type:`server`,defaultValue:n}]}),await D.copy(T.join(d,`template/extras/emailProviders/resend/service.ts`),T.join(t,`src/server/services/resend.ts`)),await D.copy(T.join(d,`template/extras/emailProviders/resend/email.tsx`),T.join(t,`src/server/auth/email.tsx`))}const rt=async({noInstall:e,installServerFiles:t}={})=>{let n=y();n.start(`Adding React Email`),await et({noInstall:e,installServerFiles:t}),n.stop(`React Email added`)};async function it(e){let t=c.projectDir,n=x();if(n.ui===`shadcn`||n.tanstackQuery)return!1;S({projectDir:t,dependencies:[`@tanstack/react-query`],devMode:!1}),S({projectDir:t,dependencies:[`@tanstack/react-query-devtools`],devMode:!0});let r=T.join(d,`template`,`extras`);c.appType===`browser`?(D.copySync(T.join(r,`config`,`get-query-client.ts`),T.join(t,`src/config/get-query-client.ts`)),D.copySync(T.join(r,`config`,`query-provider.tsx`),T.join(t,`src/config/query-provider.tsx`))):c.appType===`webviewer`&&D.copySync(T.join(r,`config`,`query-provider-vite.tsx`),T.join(t,`src/config/query-provider.tsx`));let i=e?.project??C(t),a=i.addSourceFileAtPath(T.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(k.ReturnStatement)?.getDescendantsOfKind(k.JsxOpeningElement).find(e=>e.getTagNameNode().getText()===`body`)?.getParentIfKind(k.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(k.JsxElement).find(e=>e.getOpeningElement().getTagNameNode().getText()===`MantineProvider`);e?.replaceWithText(`<QueryProvider>
|
|
8
|
+
${e.getText()}
|
|
9
|
+
</QueryProvider>`)}return e?.project||await w(i),ue({...n,tanstackQuery:!0}),!0}const at=async()=>{let e=y();e.start(`Adding Tanstack Query`),await it(),e.stop(`Tanstack Query added`)};function ot(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=ve(e.getFunction(e=>e.isDefaultExport())?.getBody()?.getFirstDescendantByKind(k.ReturnStatement)),i=r?.getFirstDescendantByKind(k.JsxOpeningFragment)?.getParentIfKind(k.JsxFragment)?.getFirstDescendantByKind(k.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 st=async({projectDir:e})=>{S({projectDir:e,dependencies:[`@clerk/nextjs`,`@clerk/themes`],devMode:!1});let t=T.join(d,`template/extras`),n=T.join(e,`src/middleware.ts`);if(D.existsSync(n))console.log(E.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=T.join(t,`src/middleware/clerk.ts`);D.copySync(e,n)}D.copySync(T.join(t,`src/app/clerk-auth`),T.join(e,`src/app/auth`)),D.copySync(T.join(t,`src/components/clerk-auth`),T.join(e,`src/components/clerk-auth`));let r=T.join(e,`src/app/layout.tsx`),i=C(e);ct(i.addSourceFileAtPath(r)),ot(i.addSourceFileAtPath(T.join(e,`src/components/AppShell/slot-header-right.tsx`)),`@/components/clerk-auth/user-menu`),ot(i.addSourceFileAtPath(T.join(e,`src/components/AppShell/slot-header-mobile-content.tsx`)),`@/components/clerk-auth/user-menu-mobile`),lt(i.addSourceFileAtPathIfExists(T.join(e,`src/server/safe-action.ts`))),await $e({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 w(i)};function ct(e){e.addImportDeclaration({namedImports:[{name:`ClerkAuthProvider`}],moduleSpecifier:`@/components/clerk-auth/clerk-provider`});let t=e.getFunction(e=>e.isDefaultExport())?.getBody()?.getFirstDescendantByKind(k.ReturnStatement)?.getDescendantsOfKind(k.JsxOpeningElement).find(e=>e.getTagNameNode().getText()===`MantineProvider`)?.getParentIfKind(k.JsxElement),n=t?.getJsxChildren().map(e=>e.getText()).filter(Boolean).join(`
|
|
16
|
+
`);t?.getChildSyntaxList()?.replaceWithText(`<ClerkAuthProvider>
|
|
17
|
+
${n}
|
|
18
|
+
</ClerkAuthProvider>`)}function lt(e){if(!e){console.log(E.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
|
+
`))}async function ut({dataApiKey:e,fmFile:t,server:n}){return pt((await Ge({adapter:new Ke({auth:{apiKey:e},db:t,server:n}),layout:``}).layouts()).layouts)}function dt(e){return`isFolder`in e?(e.folderLayoutNames??[]).flatMap(dt):[e.name]}const ft=[`API_`,`API `,`dapi_`,`dapi`];function pt(e){return e.flatMap(dt).sort((e,t)=>{let n=ft.find(t=>e.startsWith(t)),r=ft.find(e=>t.startsWith(e));return n&&r?e.localeCompare(t):n?-1:r?1:e.localeCompare(t)})}async function mt({addonName:e}){let t=e===`auth`?`FM Auth Add-on`:`ProofKit WebViewer`,n=null;if(process.platform===`win32`?n=T.join(qe.homedir(),`AppData`,`Local`,`FileMaker`,`Extensions`,`AddonModules`):process.platform===`darwin`&&(n=T.join(qe.homedir(),`Library`,`Application Support`,`FileMaker`,`Extensions`,`AddonModules`)),!n){b.warn(`Could not install the ${t} addon. You will need to do this manually.`);return}let r=e===`auth`?`ProofKitAuth`:`ProofKitWV`;await D.copy(T.join(d,`template/fm-addon/${r}`),T.join(n,r),{overwrite:!0}),console.log(``),console.log(E.bgYellow(` ACTION REQUIRED: `)),console.log(e===`auth`?`${E.yellowBright(`You must install the FM Auth addon in your FileMaker file to continue.`)} ${E.dim(`(Learn more: https://proofkit.dev/auth/fm-addon)`)}`:`${E.yellowBright(`You must install the ProofKit WebViewer addon in your FileMaker file to continue.`)} ${E.dim(`(Learn more: https://proofkit.dev/webviewer)`)}`),[`Restart FileMaker Pro (if it's currently running)`,`Open your FileMaker file, go to layout mode, and install the ${t} addon to the file`,`Come back here to continue the installation`].forEach((e,t)=>{console.log(`${t+1}. ${e}`)})}const ht=async()=>{let e=Re(`Installing files for auth...`).start(),t=c.projectDir;S({projectDir:t,dependencies:[`@node-rs/argon2`,`@oslojs/binary`,`@oslojs/crypto`,`@oslojs/encoding`,`js-cookie`],devMode:!1}),S({projectDir:t,dependencies:[`@types/js-cookie`],devMode:!0}),await D.copy(T.join(d,`template/extras/fmaddon-auth`),T.join(t,`src`));let n=C(t);await it({project:n}),ot(n.addSourceFileAtPath(T.join(t,`src/components/AppShell/slot-header-right.tsx`)),`@/components/auth/user-menu`),gt(n.addSourceFileAtPathIfExists(T.join(t,`src/server/safe-action.ts`))),await we({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 et({project:n,installServerFiles:!0}),_t(n.addSourceFileAtPath(T.join(t,`src/app/(main)/layout.tsx`))),await w(n);let r=!1;for(;!r;)if(r=await vt(t,e),r)e.text=`Successfully detected all required layouts in your FileMaker file.`;else if(!v(await p({message:`I have followed the above instructions, continue installing`,initialValue:!0})))throw new ae;await Te(),e.succeed(`Auth installed successfully`)};function gt(e){if(!e){console.log(E.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 _t(e){e.addImportDeclaration({defaultImport:`Protect`,moduleSpecifier:`@/components/auth/protect`});let t=e.getFunction(e=>e.isDefaultExport())?.getBody()?.getFirstDescendantByKind(k.ReturnStatement)?.getFirstDescendantByKind(k.JsxElement);t?.replaceWithText(`<Protect>
|
|
35
|
+
${t?.getText()}
|
|
36
|
+
</Protect>`)}async function vt(e,t){let n=x(),r=n.dataSources.filter(e=>e.type===`fm`).find(e=>e.name===`filemaker`);if(!r)return!1;n.envFile&&We.config({path:T.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 ut({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 mt({addonName:`auth`}),!1)}async function yt({options:e,noInstall:t=!1,projectDir:n=process.cwd()}){let r=x();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 bt({projectDir:n}):e.type===`fmaddon`&&await xt(),await St(),t||await ge({projectDir:n})}async function bt({projectDir:e=process.cwd()}){await st({projectDir:e}),fe({auth:{type:`clerk`}})}async function xt(){await ht(),fe({auth:{type:`fmaddon`}})}async function St(){let e=c.projectDir,t=await Ue(`src/app/(main)/**/actions.ts`,{cwd:e});for(let n of t){let t=T.join(e,n);Oe(t,De(t,`utf-8`).replace(/actionClient/g,`authedActionClient`))}}async function Ct(){let e=x();if(e.appType!==`browser`)return g(`Auth is not supported for your app type.`);if(e.ui===`shadcn`)return g(`Adding auth is not yet supported for shadcn-based projects.`);let t=c.authType??v(await h({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)??v(await h({message:`What email provider do you want to use?\n${E.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 yt({options:{type:n,emailProvider:t===`none`?void 0:t}})}else await yt({options:{type:n}})}const wt=()=>{let e=new Pe(`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(le).addOption(ce).addOption(se).action(async()=>{let e=x();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 Ct()});return e.hook(`preAction`,e=>{u(e.opts())}),e};async function Tt({url:e}){let t=Je.generate({length:18,charset:`alphanumeric`}),n=new URL(`/otto/wizard/${t}`,e.origin),r=n.toString();ie.info(`${E.bold(`If the browser window didn't open automatically, please open the following link to login into your OttoFMS server:`)}\n\n${E.cyan(r)}`),je(n.toString()).catch(()=>{});let i=y();i.start(`Waiting for you to log in using the link above`);let a=await new Promise(n=>{let r=setInterval(()=>{O.get(`${e.origin}/otto/api/cli/checkHash/${t}`,{headers:{"Accept-Encoding":`deflate`}}).then(i=>{n(i.data.response),clearTimeout(a),clearInterval(r),O.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 Et({url:e,token:t}){return(await O.get(`${e.origin}/otto/fmi/admin/api/v2/databases`,{headers:{Authorization:`Bearer ${t}`}})).data.response.databases}async function Dt({url:e,token:t}){return(await O.get(`${e.origin}/otto/api/api-key`,{headers:{Authorization:`Bearer ${t}`}})).data.response[`api-keys`]}async function Ot({url:e,filename:t}){for(ie.info(`${E.cyan(`Creating a Data API Key`)}\nEnter FileMaker credentials for ${E.bold(t)}.\n${E.dim(`The account must have the fmrest extended privilege enabled.`)}`);;){let n=v(await _({message:`Enter the account name for ${E.bold(t)}`})),r=v(await oe({message:`Enter the password for ${E.bold(n)}`}));try{return await kt({url:e,filename:t,username:n,password:r})}catch(t){if(t instanceof Ne){let n=t.response?.data&&`messages`in t.response.data?t.response.data.messages?.[0]?.text:void 0;ie.error(`${E.red(`Error creating Data API key:`)} ${n??`Error code ${t.response?.status}`}
|
|
37
|
+
${E.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 ie.error(`${E.red(`Error creating Data API key:`)} Unknown error`);if(!v(await p({message:`Do you want to try and enter credentials again?`})))throw Error(`User cancelled`)}}}async function kt({url:e,filename:t,username:n,password:r}){return{apiKey:(await O.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 At({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 O.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 jt({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 O.get(`${e.origin}/otto/api/deployment/${a}`,{headers:{Authorization:`Bearer ${r}`}});return c.parse(u.data)}const Mt=process.env.FM_HTTP_BASE_URL??`http://127.0.0.1:1365`;async function Nt(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 Pt(e){let t=await Nt(e);return t?.ok?await t.json().catch(()=>null):null}async function Ft(e=Mt){if(!(await Nt(`${e}/health`))?.ok)return{baseUrl:e,healthy:!1,connectedFiles:[]};let t=await Pt(`${e}/connectedFiles`);return{baseUrl:e,healthy:!0,connectedFiles:Array.isArray(t)?t:[]}}const It=()=>{};function Lt(e,t,n){return new Proxy(It,{get(n,r){if(!(typeof r!=`string`||r===`then`))return Lt(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 Rt=e=>Lt(e,[]);function zt(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 Bt(e){return!!e&&!Array.isArray(e)&&typeof e==`object`}function Vt(e){return typeof e==`function`}function Ht(e){return Object.assign(Object.create(null),e)}var Ut=class extends Error{};function Wt(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(Bt(e)){let t=new Ut;for(let n in e)t[n]=e[n];return t}}}function Gt(e){if(e instanceof Kt||e instanceof Error&&e.name===`TRPCError`)return e;let t=new Kt({code:`INTERNAL_SERVER_ERROR`,cause:e});return e instanceof Error&&e.stack&&(t.stack=e.stack),t}var Kt=class extends Error{constructor(e){let t=Wt(e.cause),n=e.message??t?.message??e.code;super(n,{cause:t}),this.code=e.code,this.name=`TRPCError`,this.cause||=t}};function qt(e){return`input`in e?e:{input:e,output:e}}const Jt={input:{serialize:e=>e,deserialize:e=>e},output:{serialize:e=>e,deserialize:e=>e}},Yt=({shape:e})=>e,Xt=`middlewareMarker`;function Zt(){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 Qt(e){let t=async function(t){let n,r=await t.getRawInput();try{n=await e(r)}catch(e){throw new Kt({code:`BAD_REQUEST`,cause:e})}let i=Bt(t.input)&&Bt(n)?{...t.input,...n}:n;return t.next({input:i})};return t._type=`input`,t}function $t(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 Kt({message:`Output validation failed`,code:`INTERNAL_SERVER_ERROR`,cause:e})}};return t._type=`output`,t}function en(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 A(e,t){let{middlewares:n=[],inputs:r,meta:i,...a}=t;return tn({...zt(e,a),inputs:[...e.inputs,...r??[]],middlewares:[...e.middlewares,...n],meta:e.meta&&i?{...e.meta,...i}:i??e.meta})}function tn(e={}){let t={procedure:!0,inputs:[],middlewares:[],...e};return{_def:t,input(e){let n=en(e);return A(t,{inputs:[e],middlewares:[Qt(n)]})},output(e){return A(t,{output:e,middlewares:[$t(en(e))]})},meta(e){return A(t,{meta:e})},use(e){return A(t,{middlewares:`_middlewares`in e?e._middlewares:[e]})},unstable_concat(e){return A(t,e._def)},query(e){return nn({...t,type:`query`},e)},mutation(e){return nn({...t,type:`mutation`},e)},subscription(e){return nn({...t,type:`subscription`},e)},experimental_caller(e){return A(t,{caller:e})}}}function nn(e,t){let n=A(e,{resolver:t,middlewares:[async function(e){return{marker:Xt,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=rn(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 rn(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:Gt(e),marker:Xt}}}let r=await n();if(!r)throw new Kt({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 an=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 on(e){return e._def&&`router`in e._def}const sn={_ctx:null,_errorShape:null,_meta:null,queries:{},mutations:{},subscriptions:{},errorFormatter:Yt,transformer:Jt},cn=[`then`,`call`,`apply`];function ln(e){function t(t){let n=new Set(Object.keys(t).filter(e=>cn.includes(e)));if(n.size>0)throw Error("Reserved words used in `router({})` call: "+Array.from(n).join(`, `));let r=Ht({});function i(e,t=[]){let n=Ht({});for(let[a,o]of Object.entries(e??{})){if(on(o)){n[a]=i(o._def.record,[...t,a]);continue}if(!un(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,...sn,record:a};return{...a,_def:o,createCaller:dn()({_def:o})}}return t}function un(e){return typeof e==`function`}function dn(){return function(e){let t=e._def;return function(e,n){return Rt(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=Vt(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:Gt(e),input:i[0],path:a,type:o._def.type}),e}})}}}function fn(...e){let t=zt({},...e.map(e=>e._def.record));return ln({errorFormatter:e.reduce((e,t)=>{if(t._def._config.errorFormatter&&t._def._config.errorFormatter!==Yt){if(e!==Yt&&e!==t._def._config.errorFormatter)throw Error(`You seem to have several error formatters`);return t._def._config.errorFormatter}return e},Yt),transformer:e.reduce((e,t)=>{if(t._def._config.transformer&&t._def._config.transformer!==Jt){if(e!==Jt&&e!==t._def._config.transformer)throw Error(`You seem to have several transformers`);return t._def._config.transformer}return e},Jt),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:qt(e?.transformer??Jt),isDev:e?.isDev??globalThis.process?.env.NODE_ENV!==`production`,allowOutsideOfServer:e?.allowOutsideOfServer??!1,errorFormatter:e?.errorFormatter??Yt,isServer:e?.isServer??an,$types:null,experimental:e?.experimental??{}};if(!(e?.isServer??an)&&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:tn({meta:e?.defaultMeta}),middleware:Zt(),router:ln(t),mergeRouters:fn,createCallerFactory:dn()}}};async function pn({url:e,ottoPort:t=3030}){return{fmsInfo:await hn(e),ottoInfo:await vn({url:e,ottoPort:t})}}const mn=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 hn(e){let t=new URL(e);t.pathname=`/fmws/serverinfo`;let n=await xn(t.toString()).then(e=>mn.safeParse(e.data));if(!n.success)throw console.error(`fmsInfoResult.error`,n.error.issues),new Kt({code:`BAD_REQUEST`,message:`Invalid FileMaker Server URL`});return n.data.data}const gn=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()}),_n=e.object({response:gn});async function vn({url:e,ottoPort:t=3030}){let n=await yn(e);return n||=await bn(e,t),n}async function yn(e){try{let t=new URL(e);return t.pathname=`/otto/api/info`,await xn(t.toString()).then(e=>_n.parse(e.data).response)}catch{return console.log(`unable to fetch otto4 info, trying otto3`),null}}async function bn(e,t){try{let n=new URL(e);return n.port=t?t.toString():`3030`,n.pathname=`/api/otto/info`,await xn(n.toString()).then(e=>gn.parse(e.data))}catch(e){return e instanceof Error&&console.error(`otto3 fetch error`,e.message),null}}async function xn(e){let t=new Me.Agent({rejectUnauthorized:!1});return await O.get(e,{validateStatus:null,headers:{Connection:`close`},httpsAgent:t,timeout:1e4})}const Sn=e=>e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,Cn=/^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/,wn=e=>{let t=Sn(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===`.`||Cn.test(i??``)))return`Name must consist of only lowercase alphanumeric characters, '-', and '_'`},Tn=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/,En=async e=>{let t=x(),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 h({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}))});ne(e)&&(g(),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=y();o.start(`Loading layouts from your FileMaker file...`),t.envFile&&We.config({path:T.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`),g(`Missing required environment variables. Please check your .env file.`),process.exit(1)),s.startsWith(`KEY_`)||s.startsWith(`dk_`)||(o.stop(`Failed to load layouts`),g(`Invalid API key format. API key must start with 'KEY_' or 'dk_'.`),process.exit(1));let f=await ut({dataApiKey:s,fmFile:u,server:d}),p=xe({projectDir:n,dataSourceName:r}),re=p.map(e=>e.layout).filter(Boolean),ie=p.map(e=>e.schemaName).filter(Boolean);o.stop(`Loaded layouts from your FileMaker file`),re.length>0&&m(re.join(`
|
|
45
|
+
`),`Detected existing layouts in your project`),re.push(`-`);let ae=e?.layoutName;(ae===``||!f.includes(ae??``))&&(ae=void 0);let oe=ae??v(await ee({message:`Select a new layout to read data from`,emptyMessage:`No matching layouts found.`,options:f.filter(e=>!re.includes(e)).map(e=>({label:e,value:e,keywords:[e]}))})),se=On(oe),ce=e?.schemaName||v(await _({message:`Enter a friendly name for the new schema.\n${E.dim(`This will the name by which you refer to this layout in your codebase`)}`,defaultValue:se,validate:e=>{if(e!==``){if(!Tn.test(e))return`Name must consist of only alphanumeric characters, '_', and must not start with a number`;if(ie.includes(e))return`Schema name must be unique`}}})).toString(),le=e?.valueLists??await h({message:`Should we use value lists on this layout?\n${E.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`}]}),b=l([`ignore`,`allowEmpty`,`strict`]).catch(`ignore`).parse(le);await be({runCodegen:!0,projectDir:n,dataSourceName:r,schemas:[{layoutName:oe,schemaName:ce,valueLists:b}]}),te(`Layout "${oe}" added to your project as "${ce}"`)},Dn=()=>new Pe(`layout`).alias(`schema`).description(`Add a new layout to your fmschema file`).action(async e=>{let t=e.settings;await En({settings:t})});function On(e){let t=e.replace(/[-\s]/g,`_`);for(let e of ft)t.startsWith(e)&&(t=t.replace(e,``));return t}const kn=`ProofKitDemo.fmp12`;async function An({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:kn},operation:n,source:{fileName:`ProofKitDemo.fmp12`},location:{folder:`default`,subFolder:``}}],concurrency:1,options:{closeFilesAfterBuild:!1,keepFilesClosedAfterComplete:!1,transferContainerData:!1}}],abortRemaining:!1},i=y();i.start(`Deploying ProofKit Demo file...`);let{response:{subDeploymentIds:a}}=await At({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 jt({url:e,token:t,deploymentId:o});if(!r){if(n!==`complete`)throw Error(`Deployment didn't complete`);break}}let{apiKey:s}=await kt({filename:kn,username:`admin`,password:`admin`,url:e});return i.stop(),{apiKey:s}}async function jn({projectDir:e,...t}){let n=x();if(n.appType===`webviewer`){let r=await Ft(),i=r.connectedFiles[0],o=t.name??`filemaker`;if(!t.server&&r.healthy&&i){S({projectDir:e,dependencies:[`@proofkit/fmdapi`],devMode:!1}),await ye({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),ue(n),t.layoutName&&t.schemaName)await be({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 m(`Detected local FM HTTP at ${r.baseUrl} with connected file "${i}". Edit ${E.cyan(`proofkit-typegen.config.jsonc`)} to add layouts, then run ${E.cyan(`pnpm typegen`)} or ${E.cyan(`pnpm typegen:ui`)}.`,`Local FileMaker detected`);return}if(!t.server&&a())throw Error(`No local FM HTTP connection was detected and no FileMaker server was provided. Start the local FM HTTP proxy with a connected file or rerun with --server.`);if(!t.server&&v(await h({message:`Local FM HTTP 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`){m(`You can come back later with ${E.cyan(`proofkit add data`)} after starting FM HTTP 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 Mn(t.server);if(!(i.ottoVersion&&i.ottoVersion.compare(new Be(`4.7.0`))>0||t.adminApiKey))return g(`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 Tt({url:i.url})).token,s=await Et({url:i.url,token:o}),c=s.map(e=>e.filename.replace(`.fmp12`,``)).includes(kn.replace(`.fmp12`,``)),l=t.fileName;for(;(l=t.fileName||v(await ee({message:`Which file would you like to connect to? ${E.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&&!v(await p({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 An({url:i.url,token:o,operation:c?`replace`:`install`});u=e,l=kn,t.layoutName=t.layoutName??`API_Contacts`,t.schemaName=t.schemaName??`Contacts`}else{let e=(await Dt({url:i.url,token:o})).filter(e=>e.database===l);if(!u&&e.length>0){let t=v(await ee({message:`Which OttoFMS Data API key would you like to use? ${E.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:`${E.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 Ot({filename:l,url:i.url})).apiKey}if(!u)throw Error(`No API key`);let d=r.length===0?`filemaker`:t.name??v(await _({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`:wn(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`}},te=C(e),ne=await $e({projectDir:e,project:te,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}]}),y=ne.getImportDeclaration(e=>e.getModuleSpecifierValue()===`@proofkit/fmdapi`);y?(y.getNamedImports().find(e=>e.getName()===`OttoAPIKey`)?.remove(),y.addNamedImport({name:`OttoAPIKey`,isTypeOnly:!0})):ne.addImportDeclaration({namedImports:[{name:`OttoAPIKey`,isTypeOnly:!0}],moduleSpecifier:`@proofkit/fmdapi`}),S({projectDir:e,dependencies:[`@proofkit/fmdapi`],devMode:!1}),n.dataSources.push(f),ue(n),Se({dataSourceName:d,envNames:d===`filemaker`?void 0:f.envNames}),await w(te),await En({settings:n,sourceName:d,projectDir:e,layoutName:t.layoutName,schemaName:t.schemaName,valueLists:`allowEmpty`})}async function Mn(e){let t=y(),n=null,r=null,i=null,a=e;for(;r===null;){let e=a??v(await _({message:`What is the URL of your FileMaker Server?\n${E.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{ie.error(`Invalid URL: ${e.toString()}`);continue}t.start(`Validating Server URL...`);let{fmsInfo:o,ottoInfo:s}=await pn({url:n.origin});t.stop();let c=o.ServerVersion.split(` `)[0];if(!c){ie.error(`Unable to parse FileMaker Server version`),a=void 0;continue}r=new Be(c),i=s?.Otto.version?new Be(s.Otto.version):null,a=void 0}if(n===null)throw Error(`Unable to get FileMaker Server URL`);return m(`🎉 FileMaker Server version ${r} detected \n
|
|
46
|
+
${i?`🎉 OttoFMS version ${i} detected`:`❌ OttoFMS not detected`}`),{url:n,ottoVersion:i,fmsVersion:r}}const Nn=l([`fm`,`supabase`]),Pn=async()=>{let e=Nn.parse(await h({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 jn({projectDir:process.cwd()});else throw Error(`Invalid data source`)},Fn=()=>{let e=new Pe(`data`);return e.description(`Add a new data source to your project`),e.addOption(le),e.addOption(ce),e.hook(`preAction`,(e,t)=>{u(t.opts());let n=re({commandName:`add`});t.setOptionValue(`settings`,n)}),e},In=/^[a-zA-Z_$][a-zA-Z0-9_$]*$/,Ln=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=_e({projectDir:e,dataSourceName:n.name}),a=Ce({schemaName:r,dataSourceName:n.name}),o=x();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 D.readdir(t);for await(let e of u){let n=T.join(t,e),r=await D.readFile(n,`utf8`);for(let[e,t]of Object.entries(l))r=r.replace(new RegExp(e,`g`),t);await D.writeFile(n,r,`utf8`)}let d=C(e),f=d.addSourceFileAtPath(T.join(t,c.appType===`browser`?`table.tsx`:`index.tsx`)).getVariableDeclaration(`columns`)?.getInitializerIfKind(k.ArrayLiteralExpression),p=Bn(a.filter(Boolean));for await(let e of p)f?.addElement(t=>t.inlineBlock(()=>{Rn(e)?t.write(`accessorFn: (row) => row["${e}"],`):t.write(`accessorFn: (row) => row.${e},`),t.write(`header: "${e}",`)}).write(`,`).newLine());c.appType===`webviewer`&&await it({project:d})&&await ge(),await w(d)};function Rn(e){return!In.test(e)}const zn=[`id`,`pk`,`createdat`,`updatedat`,`primarykey`,`createdby`,`modifiedby`,`creationtimestamp`,`modificationtimestamp`];function Bn(e){return e.filter(e=>!zn.includes(e.toLowerCase())||e.startsWith(`_`))}const Vn=async e=>{await Ln(e),await it()&&await ge()},Hn={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:Ln},tableEdit:{requireData:!0,label:`Basic Table (editable)`,hint:`Use to load and show multiple records with inline edit functionality`,templatePath:`nextjs/table-edit`,postIntallFn:Ln},tableInfinite:{requireData:!0,label:`Infinite Table`,hint:`Automatically load more records when the user scrolls to the bottom`,templatePath:`nextjs/table-infinite`,postIntallFn:Vn},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:Vn}},Un={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:Ln},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:Ln}};async function Wn({projectDir:e,navType:t,...n}){let r=T.join(e,`src/app/navigation.tsx`);if(!D.existsSync(r))return;let i=C(e);i.addSourceFileAtPath(r).getVariableDeclaration(t===`primary`?`primaryRoutes`:`secondaryRoutes`)?.getInitializerIfKind(k.ArrayLiteralExpression)?.addElement(e=>e.block(()=>{e.write(`
|
|
47
|
+
label: "${n.label}",
|
|
48
|
+
type: "link",
|
|
49
|
+
href: "${n.href}",`)}).write(`,`)),await w(i)}const Gn=async e=>{let t=c.projectDir,n=x();if(n.ui===`shadcn`)return g(`Adding pages is not yet supported for shadcn-based projects.`);let r=c.appType===`browser`?Object.entries(Hn):Object.entries(Un);if(r.length===0)return g(`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=v(await h({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||=v(await _({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=Fe(i.replace(`/`,``).trim()),l=e?.template??v(await h({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 g(`Page template ${l} not found`);let f,p;if(u.requireData){if(n.dataSources.length===0)return g(`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?v(await h({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 g(`Data source ${r} not found`);p=await qn({projectDir:t,dataSource:f})}let m=y();m.start(`Adding page from template`);let ee=T.join(d,`template/pages`,u.templatePath),te=c.appType===`browser`?T.join(t,`src/app/(main)`,i):T.join(t,`src/routes`,i);await D.copy(ee,te),c.appType===`browser`?s&&s!==``&&await Wn({projectDir:process.cwd(),navType:`primary`,label:s,href:i}):c.appType,await u.postIntallFn?.({projectDir:t,pageDir:te,dataSource:f,schemaName:p}),o!==n.replacedMainPage&&fe({replacedMainPage:o}),m.stop(`Added page!`);let ne=me();console.log(`\n${E.green(`Next steps:`)}\nTo preview this page, restart your dev server using the ${E.cyan(`${ne===`npm`?`npm run`:ne} dev`)} command\n`)},Kn=()=>{let e=new Pe(`page`).description(`Add a new page to your project`).action(async()=>{await Gn()});return e.addOption(le),e.addOption(ce),e.addOption(se),e.hook(`preAction`,()=>{u(e.opts()),c.baseCommand=`add`,re({commandName:`add`})}),e};async function qn({projectDir:e=process.cwd(),dataSource:t}){if(t.type===`supabase`)throw Error(`Not implemented`);let n=xe({projectDir:e,dataSourceName:t.name}).map(e=>e.schemaName).filter(Boolean);if(n.length===0){g(`This data source doesn't have any schemas to load data from`);return}return n.length===1?n[0]:v(await h({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 Jn;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Jn||={});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 Yn=(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 Xn=Yn;function Zn(){return Xn}const Qn=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=Zn(),r=Qn({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Yn?void 0:Yn].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`}),$n=e=>({status:`dirty`,value:e}),z=e=>({status:`valid`,value:e}),er=e=>e.status===`aborted`,tr=e=>e.status===`dirty`,nr=e=>e.status===`valid`,rr=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 ir=(e,t)=>{if(nr(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(rr(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 ir(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 nr(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=>nr(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 ir(n,await(rr(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 ri.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Br.create(this)}promise(){return ni.create(this,this._def)}or(e){return Hr.create([this,e],this._def)}and(e){return Gr.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 ii({...H(this._def),innerType:this,defaultValue:t,typeName:Y.ZodDefault})}brand(){return new si({typeName:Y.ZodBranded,type:this,...H(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ai({...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 ci.create(this,e)}readonly(){return li.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ar=/^c[^\s-]{8,}$/i,or=/^[0-9a-z]+$/,sr=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cr=/^[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,lr=/^[a-z0-9_-]{21}$/i,ur=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,dr=/^[-+]?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)?)??$/,fr=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let pr;const mr=/^(?:(?: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])$/,hr=/^(?:(?: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])$/,gr=/^(([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]))$/,_r=/^(([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])$/,vr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,br=`((\\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])))`,xr=RegExp(`^${br}$`);function Sr(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 Cr(e){return RegExp(`^${Sr(e)}$`)}function wr(e){let t=`${br}T${Sr(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Tr(e,t){return!!((t===`v4`||!t)&&mr.test(e)||(t===`v6`||!t)&&gr.test(e))}function Er(e,t){if(!ur.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 Dr(e,t){return!!((t===`v4`||!t)&&hr.test(e)||(t===`v6`||!t)&&_r.test(e))}var Or=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`)fr.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`)pr||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),pr.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`)cr.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`)lr.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`)ar.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`)or.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`)sr.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`?wr(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`?xr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{code:P.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Cr(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`?dr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`duration`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Tr(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`?Er(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`?Dr(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`?vr.test(e.data)||(n=this._getOrReturnCtx(e,n),I(n,{validation:`base64`,code:P.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?yr.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}};Or.create=e=>new Or({checks:[],typeName:Y.ZodString,coerce:e?.coerce??!1,...H(e)});function kr(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 Ar=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`?kr(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)}};Ar.create=e=>new Ar({checks:[],typeName:Y.ZodNumber,coerce:e?.coerce||!1,...H(e)});var jr=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}};jr.create=e=>new jr({checks:[],typeName:Y.ZodBigInt,coerce:e?.coerce??!1,...H(e)});var Mr=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)}};Mr.create=e=>new Mr({typeName:Y.ZodBoolean,coerce:e?.coerce||!1,...H(e)});var Nr=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)}};Nr.create=e=>new Nr({checks:[],coerce:e?.coerce||!1,typeName:Y.ZodDate,...H(e)});var Pr=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)}};Pr.create=e=>new Pr({typeName:Y.ZodSymbol,...H(e)});var Fr=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)}};Fr.create=e=>new Fr({typeName:Y.ZodUndefined,...H(e)});var Ir=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)}};Ir.create=e=>new Ir({typeName:Y.ZodNull,...H(e)});var Lr=class extends U{constructor(){super(...arguments),this._any=!0}_parse(e){return z(e.data)}};Lr.create=e=>new Lr({typeName:Y.ZodAny,...H(e)});var Rr=class extends U{constructor(){super(...arguments),this._unknown=!0}_parse(e){return z(e.data)}};Rr.create=e=>new Rr({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 zr=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)}};zr.create=e=>new zr({typeName:Y.ZodVoid,...H(e)});var Br=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)}};Br.create=(e,t)=>new Br({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Y.ZodArray,...H(t)});function Vr(e){if(e instanceof G){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=J.create(Vr(r))}return new G({...e._def,shape:()=>t})}else if(e instanceof Br)return new Br({...e._def,type:Vr(e.element)});else if(e instanceof J)return J.create(Vr(e.unwrap()));else if(e instanceof ri)return ri.create(Vr(e.unwrap()));else if(e instanceof Kr)return Kr.create(e.items.map(e=>Vr(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 Vr(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 $r(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 Hr=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}};Hr.create=(e,t)=>new Hr({options:e,typeName:Y.ZodUnion,...H(t)});const K=e=>e instanceof Zr?K(e.schema):e instanceof q?K(e.innerType()):e instanceof Qr?[e.value]:e instanceof ei?e.options:e instanceof ti?j.objectValues(e.enum):e instanceof ii?K(e._def.innerType):e instanceof Fr?[void 0]:e instanceof Ir?[null]:e instanceof J?[void 0,...K(e.unwrap())]:e instanceof ri?[null,...K(e.unwrap())]:e instanceof si||e instanceof li?K(e.unwrap()):e instanceof ai?K(e._def.innerType):[];var Ur=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 Wr(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=Wr(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=Wr(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 Gr=class extends U{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(er(e)||er(r))return R;let i=Wr(e.value,r.value);return i.valid?((tr(e)||tr(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}))}};Gr.create=(e,t,n)=>new Gr({left:e,right:t,typeName:Y.ZodIntersection,...H(n)});var Kr=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})}};Kr.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Kr({items:e,typeName:Y.ZodTuple,rest:null,...H(t)})};var qr=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:Or.create(),valueType:t,typeName:Y.ZodRecord,...H(n)})}},Jr=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}}}};Jr.create=(e,t,n)=>new Jr({valueType:t,keyType:e,typeName:Y.ZodMap,...H(n)});var Yr=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)}};Yr.create=(e,t)=>new Yr({valueType:e,minSize:null,maxSize:null,typeName:Y.ZodSet,...H(t)});var Xr=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 Qn({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Zn(),Yn].filter(e=>!!e),issueData:{code:P.invalid_arguments,argumentsError:n}})}function r(e,n){return Qn({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Zn(),Yn].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 ni){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:Kr.create(t).rest(Rr.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||Kr.create([]).rest(Rr.create()),returns:n||Rr.create(),typeName:Y.ZodFunction,...H(r)})}},Zr=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})}};Zr.create=(e,t)=>new Zr({getter:e,typeName:Y.ZodLazy,...H(t)});var Qr=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}};Qr.create=(e,t)=>new Qr({value:e,typeName:Y.ZodLiteral,...H(t)});function $r(e,t){return new ei({values:e,typeName:Y.ZodEnum,...H(t)})}var ei=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})}};ei.create=$r;var ti=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}};ti.create=(e,t)=>new ti({values:e,typeName:Y.ZodNativeEnum,...H(t)});var ni=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})))}};ni.create=(e,t)=>new ni({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`?$n(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`?$n(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(!nr(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=>nr(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 ri=class extends U{_parse(e){return this._getType(e)===M.null?z(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ri.create=(e,t)=>new ri({innerType:e,typeName:Y.ZodNullable,...H(t)});var ii=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}};ii.create=(e,t)=>new ii({innerType:e,typeName:Y.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...H(t)});var ai=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 rr(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}};ai.create=(e,t)=>new ai({innerType:e,typeName:Y.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...H(t)});var oi=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}}};oi.create=e=>new oi({typeName:Y.ZodNaN,...H(e)});var si=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}},ci=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(),$n(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})}},li=class extends U{_parse(e){let t=this._def.innerType._parse(e),n=e=>(nr(e)&&(e.value=Object.freeze(e.value)),e);return rr(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};li.create=(e,t)=>new li({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=Or.create;Ar.create,oi.create,jr.create;const ui=Mr.create;Nr.create,Pr.create,Fr.create,Ir.create;const di=Lr.create;Rr.create,W.create,zr.create;const Z=Br.create,Q=G.create;G.strictCreate,Hr.create;const fi=Ur.create;Gr.create,Kr.create;const $=qr.create;Jr.create,Yr.create,Xr.create,Zr.create;const pi=Qr.create,mi=ei.create;ti.create,ni.create,q.create,J.create,ri.create,q.createWithPreprocess,ci.create;const hi=mi([`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.`);fi(`type`,[Q({path:X(),content:X().optional(),type:hi.extract([`registry:file`,`registry:page`]),target:X()}),Q({path:X(),content:X().optional(),type:hi.exclude([`registry:file`,`registry:page`]),target:X().optional()})]);const gi=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(),di()).optional(),plugins:Z(X()).optional()}).optional()}).optional(),cssVars:Q({theme:$(X(),X()).optional(),light:$(X(),X()).optional(),dark:$(X(),X()).optional()}).optional(),css:$(X(),di()).optional(),envVars:$(X(),X()).optional(),meta:$(X(),di()).optional(),categories:Z(X()).optional()}),_i=fi(`type`,[Q({sourceFileName:X(),destinationPath:X().optional(),type:hi.extract([`registry:file`,`registry:page`]),handlebars:ui().optional()}),Q({sourceFileName:X(),destinationPath:X().optional(),type:hi.exclude([`registry:file`,`registry:page`]),handlebars:ui().optional()})]),vi=(e,t)=>Q({action:pi(e),data:t,_from:X().optional()}),yi=fi(`action`,[vi(`next-steps`,Q({message:X()})),vi(`package.json script`,Q({scriptName:X(),scriptCommand:X()})),vi(`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:mi([`server`,`client`]),addToRuntimeEnv:ui().optional().describe(`Whether to add the env to the runtime env.`)}).array()})),vi(`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.`)}))]),bi=mi([`component`,`page`,`utility`,`hook`,`email`]),xi=mi([`next-pages`,`next-app`,`manual`]),Si=gi.extend({title:X(),description:X().optional(),category:bi,files:Z(_i),registryType:hi,postInstall:Z(yi).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(xi).optional(),schemaRequired:ui().optional().describe(`Whether this template requires a database schema to be selected`)}),Ci=Q({name:X(),title:X(),category:bi,description:X().optional()}).array(),wi=ke(import.meta.url),Ti=T.dirname(wi);T.resolve(Ti,`../templates`);function Ei(e){return e.replace(/^\/+|\/+$/g,``)}function Di(e){return(e.registryDependencies??[]).filter(e=>e.startsWith(`{proofkit}/r/`)).map(e=>e.replace(`{proofkit}/r/`,``)).map(Ei)}const Oi={"{{schema.schemaName}}":`__HB_SCHEMA_NAME__`,"{{schema.sourceName}}":`__HB_SOURCE_NAME__`,"{{schema.clientSuffix}}":`__HB_CLIENT_SUFFIX__`};function ki(e){let t=e;for(let[e,n]of Object.entries(Oi))t=t.replace(new RegExp(Ai(n),`g`),e);return t}function Ai(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}async function ji(e,t){let n=[`shadcn@latest`,`add`,...Array.isArray(e)?e:[e]];try{await Ae(`pnpm`,[`dlx`,...n],{stdio:`inherit`,cwd:c.projectDir??process.cwd()})}catch(e){throw b.error(`Failed to run shadcn add: ${e}`),e}}function Mi(){let e;try{e=x().registryUrl??f}catch{e=f}return e.endsWith(`/`)?e.slice(0,-1):e}function Ni(){let e=T.join(c.projectDir,`components.json`);return JSON.parse(Ee.readFileSync(e,`utf8`))}const Pi=Xe({"@get/meta/:name":{output:Si},"@get/":{output:Ci}}),Fi=Ye({baseURL:`${Mi()}/r`,schema:Pi});async function Ii(e){let t=await Fi(`@get/meta/:name`,{params:{name:e}});if(t.error){if(t.error.status===404)return null;throw Error(t.error.message)}return t.data}Ze.registerHelper(`eq`,(e,t)=>e===t),Ze.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 Li=[`id`,`pk`,`createdat`,`updatedat`,`primarykey`,`createdby`,`modifiedby`,`creationtimestamp`,`modificationtimestamp`];function Ri(e){return e.filter(e=>!Li.includes(e.toLowerCase())||e.startsWith(`_`))}function zi(e){let{dataSource:t,schemaName:n}=e,r=_e({projectDir:c.projectDir??process.cwd(),dataSourceName:t.name}),i=Ce({schemaName:n,dataSourceName:t.name}).filter(Boolean);return{sourceName:t.name,schemaName:n,clientSuffix:r,allFieldNames:i,fieldNames:Ri(i)}}function Bi(e){return{proofkit:x(),shadcn:Ni(),schema:e?zi(e):{sourceName:`UnknownDataSource`,schemaName:`UnknownSchema`,clientSuffix:`UnknownClientSuffix`,allFieldNames:[`UnknownFieldName`],fieldNames:[`UnknownFieldName`]}}}async function Vi(e,t){let n=Hi(e,t),r=await D.readFile(n,`utf8`);r=ki(r);let i=Ze.compile(r)(t);await D.writeFile(n,i)}function Hi(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 T.join(r,e,n)}return o.startsWith(`/`)||o.includes(`src/`)?T.join(r,o,n):T.join(r,`src`,o,n)}switch(e.type){case`registry:lib`:return T.join(r,`src`,`lib`,n);case`registry:file`:return T.join(r,`src`,n);case`registry:page`:{let e=`routeName`in t?t.routeName:void 0;if(e){let t=e===`/`?``:e;return T.join(r,`src`,`app`,`(main)`,t,n)}return T.join(r,`src`,`app`,n)}case`registry:block`:return T.join(r,`src`,`components`,`blocks`,n);case`registry:component`:return T.join(r,`src`,`components`,n);case`registry:ui`:return T.join(r,`src`,`components`,n);case`registry:hook`:return T.join(r,`src`,`hooks`,n);case`registry:theme`:return T.join(r,`src`,`theme`,n);case`registry:style`:return T.join(r,`src`,`styles`,n);default:return n}}function Ui(e){let t=T.join(c.projectDir,`package.json`),n=JSON.parse(Ee.readFileSync(t,`utf8`));n.scripts[e.data.scriptName]=e.data.scriptCommand,Ee.writeFileSync(t,JSON.stringify(n,null,2))}async function Wi(e){let{parentTag:t,imports:n,providerCloseTag:r,providerOpenTag:i}=e.data;try{let e=c.projectDir,a=C(e),o=(e=>e.startsWith(`@/`)?e.replace(`@/`,`src/`):e.startsWith(`./`)?e.substring(2):e)(Ni().aliases.components),s=T.join(e,o,`providers.tsx`),l=a.addSourceFileAtPath(s);for(let e of n){let t={moduleSpecifier:e.moduleSpecifier,kind:He.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){b.warn(`No default export function found in ${s}`);return}let d=u?.getBody()?.getFirstDescendantByKind(k.ReturnStatement);if(!d){b.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(k.JsxOpeningElement).find(t=>t.getTagNameNode().getText()===e)?.getParentIfKind(k.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()===k.ParenthesizedExpression,n;n=t?e.asKindOrThrow(k.ParenthesizedExpression).getExpression().getText():e.getText();let a=`return (
|
|
53
|
+
${i}
|
|
54
|
+
${n}
|
|
55
|
+
${r}
|
|
56
|
+
);`;d?.replaceWithText(a)}else b.warn(`No return expression found to wrap`)}await w(a),b.success(`Successfully wrapped provider in ${s}`)}catch(e){throw b.error(`Failed to wrap provider: ${e}`),e}}async function Gi(e){e.action===`package.json script`?Ui(e):e.action===`wrap provider`?await Wi(e):e.action===`next-steps`?b.info(e.data.message):e.action===`env`?await $e({envs:e.data.envs}):b.error(`Unknown post-install step: ${e}`)}async function Ki(){await D.pathExists(`proofkit.json`)||(ue(pe),de())}async function qi(){let e=c.projectDir??process.cwd();if(!await D.pathExists(T.join(e,`components.json`)))throw Error("Shadcn is not installed. Please run `pnpm dlx shadcn@latest init` to install it.");await Ki()}async function Ji({projectDir:e=process.cwd(),dataSource:t}){if(t.type===`supabase`)throw Error(`Not implemented`);let n=xe({projectDir:e,dataSourceName:t.name}).map(e=>e.schemaName).filter(e=>!!e);if(n.length===0){g(`This data source doesn't have any schemas to load data from`);return}return n.length===1?n[0]:v(await h({message:`Which schema should this template use?`,options:n.map(e=>({label:e,value:e}))}))}async function Yi(e){let t=Re(`Validating template`).start();try{await qi();let n=await Ii(e);if(!n){t.fail(`Template ${e} not found in the ProofKit registry`);return}if(n.minimumProofKitVersion&&ze.gt(n.minimumProofKitVersion,he())){b.error(`Template ${e} requires ProofKit version ${n.minimumProofKitVersion}, but you are using version ${he()}`),t.fail(`Template is not compatible with your ProofKit version`);return}t.succeed();let r=Di(n),i=x().registryTemplates,a,o,s,l;if(n.schemaRequired){let e=x();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?v(await h({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 Ji({projectDir:c.projectDir,dataSource:a}),!o){t.fail(`Schema selection was cancelled`);return}}n.category===`page`&&(s=v(await _({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=Fe(s.replace(`/`,``).trim()));let u=new URL(`${Mi()}/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 Yi(`utils/t3-env`),i=x().registryTemplates),await ji([u.toString()],n.title);let d=n.files.filter(e=>e.handlebars);if(d.length>0){let t={...a&&o?Bi({dataSource:a,schemaName:o}):Bi(),...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 Vi(e,t)}if(n.category===`page`&&s&&l&&await Wn({projectDir:c.projectDir,navType:`primary`,label:l,href:`/${s}`}),n.postInstall)for(let e of n.postInstall)e._from&&i.includes(e._from)||await Gi(e);fe({registryTemplates:Le([...i,e,...r])})}catch(e){t.fail(`Failed to fetch template metadata.`),b.error(e)}}async function Xi(){let{data:e,error:t}=await Fi(`@get/`);if(t)throw Error(`Failed to fetch items from registry: ${t.message}`);return e}const Zi=async e=>{let t=x(),n=Re(`Loading available components...`).start(),r;try{r=await Xi()}catch(e){n.fail(`Failed to load registry components`),b.error(e);return}let i=r.filter(e=>!t.registryTemplates.includes(e.name)),a=Ie(i,e=>e.category),o=Le(i.map(e=>e.category));n.succeed();let s=v(await h({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:Fe(e),value:e}))]}));if(s===`schema`)await En();else if(s===`data`)await Pn();else if(o.includes(s)){let e=a[s];await Yi(v(await h({message:`Select a ${s} to add to your project`,options:e.map(e=>({label:e.title,hint:e.description,value:e.name}))})))}else b.error(`Could not find any available components in the category "${s}"`)},Qi=async(e,t)=>{if(e===`tanstack-query`)return await at();if(e!==void 0)return await Yi(e);let n;try{n=x()}catch{return await qi(),await Zi(t)}if(n.ui===`shadcn`)return await Zi(t);re({commandName:`add`});let r=v(await h({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 Ct():r===`data`?await Pn():r===`page`?await Gn():r===`schema`?await En():r===`react-email`&&await rt({noInstall:t?.noInstall})},$i=()=>{let e=new Pe(`add`).description(`Add a new component to your project`).argument(`[name]`,`Type of component to add`).addOption(le).addOption(ce).addOption(se).option(`--noInstall`,`Do not run your package manager install command`,!1).action(async(e,t)=>{await Qi(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(wt()),e.addCommand(Kn()),e.addCommand(Dn()),e.addCommand(Fn()),e};export{$i as makeAddCommand,Qi as runAdd};
|
|
57
|
+
//# sourceMappingURL=add-CfoeMDFa.js.map
|