@emdashjetpack/newsletter 0.0.0-stage → 0.5.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 emdashJetpack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # Newsletter
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Newsletter collects double opt-in subscriptions and can email confirmed subscribers when you publish a post. Confirmation and digest messages use your site's EmDash email provider.
4
+
5
+ ## Setup
6
+
7
+ 1. Configure your site's [EmDash email provider](https://docs.emdashcms.com/guides/email/) and send a test email.
8
+ 2. Install Newsletter through EmDash Admin's Registry when available, or run `npm install @emdashjetpack/newsletter` and register its default descriptor under `sandboxed` in your EmDash integration. Use one install method per site and confirm Newsletter is active in **Plugins**. [npm configuration example](../../README.md#install-add-ons-from-npm)
9
+ 3. Install the [Jetpack Astro companion](../astro/README.md#setup). Add `NewsletterForm.astro` to your signup page and register `@emdashjetpack/astro/integration` to serve the confirmation and unsubscribe page. For a Registry install, set `PUBLIC_JETPACK_NEWSLETTER_PLUGIN_ID` to the Newsletter runtime ID shown in its Admin URL, then restart or rebuild the site.
10
+
11
+ ## Verify delivery
12
+
13
+ 1. Submit a test address through the signup form. Check that **Newsletter** in EmDash Admin shows a pending subscriber.
14
+ 2. Open the email's confirmation link and submit the confirmation form. Check that the subscriber is confirmed.
15
+ 3. On a test site, enable **Queue digest email on publish** under **Newsletter**, save, and publish a post. Wait for the scheduler, then check the inbox and **Recent digest deliveries**.
16
+ 4. Open the digest's unsubscribe link and submit the unsubscribe form. Check that the admin count shows the subscriber as unsubscribed.
17
+
18
+ ## Subscriber data
19
+
20
+ The plugin stores subscriber addresses, list IDs, subscription status, confirmation and unsubscribe tokens, and digest delivery state in plugin storage. Its content permission resolves published post links. Email goes through the provider configured in EmDash.
21
+
22
+ ## Subscription and digest behavior
23
+
24
+ The public subscribe route accepts an email and an optional `listId`, which defaults to `default`. One normalized email belongs to one list per site. A request for a different list returns `list_mismatch` and preserves the existing subscription. A confirmed subscriber on the same list receives `confirmed` without another email. An unsubscribed address can join its original list again through double opt-in. This keeps the subscriber record and issues fresh confirmation and unsubscribe links.
25
+
26
+ Publish digests go to currently confirmed subscribers on the configured list. Newsletter admin shows pending, delivered, failed, uncertain, and skipped recipient counts for the ten most recent jobs. An interrupted send has an uncertain outcome and is kept for review. Retryable sends have a three-attempt limit.
@@ -0,0 +1,5 @@
1
+ // Auto-generated by emdash-plugin build. Do not edit.
2
+ import type { PluginDescriptor } from "emdash";
3
+
4
+ declare const descriptor: PluginDescriptor;
5
+ export default descriptor;
package/dist/index.mjs ADDED
@@ -0,0 +1,114 @@
1
+ // Auto-generated by emdash-plugin build. Do not edit.
2
+ // Source: emdash-plugin.jsonc + package.json
3
+ //
4
+ // Default-exports a sandboxed plugin descriptor. Pass it directly into
5
+ // emdash's `plugins:` or `sandboxed:` array — no factory call needed.
6
+
7
+ /** @type {import("emdash").PluginDescriptor} */
8
+ const descriptor = Object.freeze({
9
+ "id": "emdashjetpack-newsletter",
10
+ "displayName": "EmDash Jetpack Newsletter",
11
+ "description": "Collect confirmed newsletter subscriptions and send optional publish digests through your site's EmDash email provider.",
12
+ "version": "0.5.2",
13
+ "format": "standard",
14
+ "entrypoint": "@emdashjetpack/newsletter/sandbox",
15
+ "capabilities": [
16
+ "content:read",
17
+ "email:send"
18
+ ],
19
+ "allowedHosts": [],
20
+ "storage": {
21
+ "digest_jobs": {
22
+ "indexes": [
23
+ "status",
24
+ "createdAt",
25
+ "claimedUntil"
26
+ ]
27
+ },
28
+ "subscribers": {
29
+ "indexes": [
30
+ "email",
31
+ "listId",
32
+ "status",
33
+ "updatedAt",
34
+ "confirmToken",
35
+ "unsubscribeToken"
36
+ ],
37
+ "uniqueIndexes": [
38
+ "email"
39
+ ]
40
+ }
41
+ },
42
+ "hooks": [
43
+ "plugin:activate",
44
+ "plugin:deactivate",
45
+ "content:afterPublish",
46
+ "cron"
47
+ ],
48
+ "routes": [
49
+ {
50
+ "name": "admin",
51
+ "methods": [
52
+ "POST"
53
+ ],
54
+ "request": {
55
+ "body": "json"
56
+ }
57
+ },
58
+ {
59
+ "name": "subscribe",
60
+ "methods": [
61
+ "POST"
62
+ ],
63
+ "request": {
64
+ "body": "json",
65
+ "maxBytes": 2048
66
+ },
67
+ "public": true
68
+ },
69
+ {
70
+ "name": "confirm",
71
+ "methods": [
72
+ "GET"
73
+ ],
74
+ "request": {
75
+ "body": "none"
76
+ },
77
+ "response": "raw",
78
+ "public": true
79
+ },
80
+ {
81
+ "name": "unsubscribe",
82
+ "methods": [
83
+ "GET"
84
+ ],
85
+ "request": {
86
+ "body": "none"
87
+ },
88
+ "response": "raw",
89
+ "public": true
90
+ },
91
+ {
92
+ "name": "subscription-action",
93
+ "methods": [
94
+ "POST"
95
+ ],
96
+ "request": {
97
+ "body": "form-data",
98
+ "maxBytes": 1024
99
+ },
100
+ "response": "raw",
101
+ "public": true
102
+ },
103
+ "health"
104
+ ],
105
+ "adminPages": [
106
+ {
107
+ "path": "/newsletter",
108
+ "label": "Newsletter",
109
+ "icon": "mail"
110
+ }
111
+ ]
112
+ });
113
+
114
+ export default descriptor;
@@ -0,0 +1,112 @@
1
+ {
2
+ "id": "emdashjetpack-newsletter",
3
+ "version": "0.5.2",
4
+ "declaredAccess": {
5
+ "content": {
6
+ "read": {}
7
+ },
8
+ "email": {
9
+ "send": {}
10
+ }
11
+ },
12
+ "capabilities": [
13
+ "content:read",
14
+ "email:send"
15
+ ],
16
+ "allowedHosts": [],
17
+ "storage": {
18
+ "digest_jobs": {
19
+ "indexes": [
20
+ "status",
21
+ "createdAt",
22
+ "claimedUntil"
23
+ ]
24
+ },
25
+ "subscribers": {
26
+ "indexes": [
27
+ "email",
28
+ "listId",
29
+ "status",
30
+ "updatedAt",
31
+ "confirmToken",
32
+ "unsubscribeToken"
33
+ ],
34
+ "uniqueIndexes": [
35
+ "email"
36
+ ]
37
+ }
38
+ },
39
+ "hooks": [
40
+ "plugin:activate",
41
+ "plugin:deactivate",
42
+ "content:afterPublish",
43
+ "cron"
44
+ ],
45
+ "routes": [
46
+ {
47
+ "name": "admin",
48
+ "methods": [
49
+ "POST"
50
+ ],
51
+ "request": {
52
+ "body": "json"
53
+ }
54
+ },
55
+ {
56
+ "name": "subscribe",
57
+ "methods": [
58
+ "POST"
59
+ ],
60
+ "request": {
61
+ "body": "json",
62
+ "maxBytes": 2048
63
+ },
64
+ "public": true
65
+ },
66
+ {
67
+ "name": "confirm",
68
+ "methods": [
69
+ "GET"
70
+ ],
71
+ "request": {
72
+ "body": "none"
73
+ },
74
+ "response": "raw",
75
+ "public": true
76
+ },
77
+ {
78
+ "name": "unsubscribe",
79
+ "methods": [
80
+ "GET"
81
+ ],
82
+ "request": {
83
+ "body": "none"
84
+ },
85
+ "response": "raw",
86
+ "public": true
87
+ },
88
+ {
89
+ "name": "subscription-action",
90
+ "methods": [
91
+ "POST"
92
+ ],
93
+ "request": {
94
+ "body": "form-data",
95
+ "maxBytes": 1024
96
+ },
97
+ "response": "raw",
98
+ "public": true
99
+ },
100
+ "health"
101
+ ],
102
+ "admin": {
103
+ "pages": [
104
+ {
105
+ "path": "/newsletter",
106
+ "label": "Newsletter",
107
+ "icon": "mail"
108
+ }
109
+ ],
110
+ "widgets": []
111
+ }
112
+ }
@@ -0,0 +1,6 @@
1
+ import { SandboxedPlugin } from "emdash/plugin";
2
+
3
+ //#region src/plugin.d.ts
4
+ declare const plugin: SandboxedPlugin;
5
+ //#endregion
6
+ export { plugin as default };
@@ -0,0 +1 @@
1
+ function e(e={}){let t=[];return new Headers(e.headers).forEach((e,n)=>t.push([n,e])),{__emdashPluginResponse:!0,status:e.status??200,headers:t,body:e.body??null}}function t(e){return e}const n=new TextEncoder;async function r(e){let t=await crypto.subtle.digest(`SHA-256`,n.encode(e));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function i(e=24){let t=new Uint8Array(e);return crypto.getRandomValues(t),Array.from(t).map(e=>e.toString(16).padStart(2,`0`)).join(``)}var a;(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})(a||={});var o;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(o||={});const s=a.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),c=e=>{switch(typeof e){case`undefined`:return s.undefined;case`string`:return s.string;case`number`:return Number.isNaN(e)?s.nan:s.number;case`boolean`:return s.boolean;case`function`:return s.function;case`bigint`:return s.bigint;case`symbol`:return s.symbol;case`object`:return Array.isArray(e)?s.array:e===null?s.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?s.promise:typeof Map<`u`&&e instanceof Map?s.map:typeof Set<`u`&&e instanceof Set?s.set:typeof Date<`u`&&e instanceof Date?s.date:s.object;default:return s.unknown}},l=a.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 u=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,a.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t={},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()}};u.create=e=>new u(e);const d=(e,t)=>{let n;switch(e.code){case l.invalid_type:n=e.received===s.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case l.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,a.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:n=`Unrecognized key(s) in object: ${a.joinValues(e.keys,`, `)}`;break;case l.invalid_union:n=`Invalid input`;break;case l.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${a.joinValues(e.options)}`;break;case l.invalid_enum_value:n=`Invalid enum value. Expected ${a.joinValues(e.options)}, received '${e.received}'`;break;case l.invalid_arguments:n=`Invalid function arguments`;break;case l.invalid_return_type:n=`Invalid function return type`;break;case l.invalid_date:n=`Invalid date`;break;case l.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}"`:a.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case l.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 l.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 l.custom:n=`Invalid input`;break;case l.invalid_intersection_types:n=`Intersection results could not be merged`;break;case l.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case l.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,a.assertNever(e)}return{message:n}};let f=d;function p(){return f}const ee=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 m(e,t){let n=p(),r=ee({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===d?void 0:d].filter(e=>!!e)});e.common.issues.push(r)}var h=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 g;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 g;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 g=Object.freeze({status:`aborted`}),te=e=>({status:`dirty`,value:e}),_=e=>({status:`valid`,value:e}),ne=e=>e.status===`aborted`,re=e=>e.status===`dirty`,v=e=>e.status===`valid`,y=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 x=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 ie=(e,t)=>{if(v(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 u(e.common.issues),this._error}}};function S(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 C=class{get description(){return this._def.description}_getType(e){return c(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new h,ctx:{common:e.parent.common,data:e.data,parsedType:c(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(y(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:c(e)};return ie(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:c(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return v(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=>v(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:c(e)},r=this._parse({data:e,path:n.path,parent:n});return ie(n,await(y(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:l.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 z({schema:this,typeName:U.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 B.create(this,this._def)}nullable(){return V.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return k.create(this)}promise(){return R.create(this,this._def)}or(e){return M.create([this,e],this._def)}and(e){return Re.create(this,e,this._def)}transform(e){return new z({...S(this._def),schema:this,typeName:U.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new Ge({...S(this._def),innerType:this,defaultValue:t,typeName:U.ZodDefault})}brand(){return new qe({typeName:U.ZodBranded,type:this,...S(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new H({...S(this._def),innerType:this,catchValue:t,typeName:U.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Je.create(this,e)}readonly(){return Ye.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ae=/^c[^\s-]{8,}$/i,oe=/^[0-9a-z]+$/,se=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ce=/^[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,le=/^[a-z0-9_-]{21}$/i,ue=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,de=/^[-+]?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)?)??$/,fe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let pe;const me=/^(?:(?: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])$/,he=/^(?:(?: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])$/,ge=/^(([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]))$/,_e=/^(([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])$/,ve=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ye=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,be=`((\\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])))`,xe=RegExp(`^${be}$`);function Se(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 Ce(e){return RegExp(`^${Se(e)}$`)}function we(e){let t=`${be}T${Se(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Te(e,t){return!!((t===`v4`||!t)&&me.test(e)||(t===`v6`||!t)&&ge.test(e))}function Ee(e,t){if(!ue.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 De(e,t){return!!((t===`v4`||!t)&&he.test(e)||(t===`v6`||!t)&&_e.test(e))}var w=class e extends C{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==s.string){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.string,received:t.parsedType}),g}let t=new h,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.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),m(n,{code:l.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?m(n,{code:l.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&m(n,{code:l.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)fe.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`email`,code:l.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)pe||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),pe.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`emoji`,code:l.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ce.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`uuid`,code:l.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)le.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`nanoid`,code:l.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)ae.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`cuid`,code:l.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)oe.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`cuid2`,code:l.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)se.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`ulid`,code:l.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),m(n,{validation:`url`,code:l.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),m(n,{validation:`regex`,code:l.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),m(n,{code:l.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),m(n,{code:l.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),m(n,{code:l.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?we(r).test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:l.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?xe.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:l.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Ce(r).test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{code:l.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?de.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`duration`,code:l.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Te(e.data,r.version)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`ip`,code:l.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ee(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`jwt`,code:l.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?De(e.data,r.version)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`cidr`,code:l.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?ve.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`base64`,code:l.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?ye.test(e.data)||(n=this._getOrReturnCtx(e,n),m(n,{validation:`base64url`,code:l.invalid_string,message:r.message}),t.dirty()):a.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:l.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}};w.create=e=>new w({checks:[],typeName:U.ZodString,coerce:e?.coerce??!1,...S(e)});function Oe(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 ke=class e extends C{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)!==s.number){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.number,received:t.parsedType}),g}let t,n=new h;for(let r of this._def.checks)r.kind===`int`?a.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),m(t,{code:l.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),m(t,{code:l.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),m(t,{code:l.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Oe(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),m(t,{code:l.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),m(t,{code:l.not_finite,message:r.message}),n.dirty()):a.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`&&a.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)}};ke.create=e=>new ke({checks:[],typeName:U.ZodNumber,coerce:e?.coerce||!1,...S(e)});var Ae=class e extends C{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)!==s.bigint)return this._getInvalidInput(e);let t,n=new h;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),m(t,{code:l.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),m(t,{code:l.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),m(t,{code:l.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):a.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.bigint,received:t.parsedType}),g}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}};Ae.create=e=>new Ae({checks:[],typeName:U.ZodBigInt,coerce:e?.coerce??!1,...S(e)});var je=class extends C{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==s.boolean){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.boolean,received:t.parsedType}),g}return _(e.data)}};je.create=e=>new je({typeName:U.ZodBoolean,coerce:e?.coerce||!1,...S(e)});var Me=class e extends C{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==s.date){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.date,received:t.parsedType}),g}if(Number.isNaN(e.data.getTime()))return m(this._getOrReturnCtx(e),{code:l.invalid_date}),g;let t=new h,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),m(n,{code:l.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),m(n,{code:l.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):a.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)}};Me.create=e=>new Me({checks:[],coerce:e?.coerce||!1,typeName:U.ZodDate,...S(e)});var Ne=class extends C{_parse(e){if(this._getType(e)!==s.symbol){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.symbol,received:t.parsedType}),g}return _(e.data)}};Ne.create=e=>new Ne({typeName:U.ZodSymbol,...S(e)});var T=class extends C{_parse(e){if(this._getType(e)!==s.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.undefined,received:t.parsedType}),g}return _(e.data)}};T.create=e=>new T({typeName:U.ZodUndefined,...S(e)});var E=class extends C{_parse(e){if(this._getType(e)!==s.null){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.null,received:t.parsedType}),g}return _(e.data)}};E.create=e=>new E({typeName:U.ZodNull,...S(e)});var Pe=class extends C{constructor(){super(...arguments),this._any=!0}_parse(e){return _(e.data)}};Pe.create=e=>new Pe({typeName:U.ZodAny,...S(e)});var D=class extends C{constructor(){super(...arguments),this._unknown=!0}_parse(e){return _(e.data)}};D.create=e=>new D({typeName:U.ZodUnknown,...S(e)});var O=class extends C{_parse(e){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.never,received:t.parsedType}),g}};O.create=e=>new O({typeName:U.ZodNever,...S(e)});var Fe=class extends C{_parse(e){if(this._getType(e)!==s.undefined){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.void,received:t.parsedType}),g}return _(e.data)}};Fe.create=e=>new Fe({typeName:U.ZodVoid,...S(e)});var k=class e extends C{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==s.array)return m(t,{code:l.invalid_type,expected:s.array,received:t.parsedType}),g;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(m(t,{code:e?l.too_big:l.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&&(m(t,{code:l.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&&(m(t,{code:l.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 x(t,e,t.path,n)))).then(e=>h.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new x(t,e,t.path,n)));return h.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)}};k.create=(e,t)=>new k({type:e,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...S(t)});function A(e){if(e instanceof j){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=B.create(A(r))}return new j({...e._def,shape:()=>t})}else if(e instanceof k)return new k({...e._def,type:A(e.element)});else if(e instanceof B)return B.create(A(e.unwrap()));else if(e instanceof V)return V.create(A(e.unwrap()));else if(e instanceof P)return P.create(e.items.map(e=>A(e)));else return e}var j=class e extends C{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:a.objectKeys(e)},this._cached}_parse(e){if(this._getType(e)!==s.object){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.object,received:t.parsedType}),g}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof O&&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 x(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof O){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&&(m(n,{code:l.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 x(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=>h.mergeObjectSync(t,e)):h.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:U.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 a.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 a.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return A(this)}partial(t){let n={};for(let e of a.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 a.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof B;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return Ue(a.objectKeys(this.shape))}};j.create=(e,t)=>new j({shape:()=>e,unknownKeys:`strip`,catchall:O.create(),typeName:U.ZodObject,...S(t)}),j.strictCreate=(e,t)=>new j({shape:()=>e,unknownKeys:`strict`,catchall:O.create(),typeName:U.ZodObject,...S(t)}),j.lazycreate=(e,t)=>new j({shape:e,unknownKeys:`strip`,catchall:O.create(),typeName:U.ZodObject,...S(t)});var M=class extends C{_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 u(e.ctx.common.issues));return m(t,{code:l.invalid_union,unionErrors:n}),g}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 u(e));return m(t,{code:l.invalid_union,unionErrors:i}),g}}get options(){return this._def.options}};M.create=(e,t)=>new M({options:e,typeName:U.ZodUnion,...S(t)});const N=e=>e instanceof F?N(e.schema):e instanceof z?N(e.innerType()):e instanceof I?[e.value]:e instanceof L?e.options:e instanceof We?a.objectValues(e.enum):e instanceof Ge?N(e._def.innerType):e instanceof T?[void 0]:e instanceof E?[null]:e instanceof B?[void 0,...N(e.unwrap())]:e instanceof V?[null,...N(e.unwrap())]:e instanceof qe||e instanceof Ye?N(e.unwrap()):e instanceof H?N(e._def.innerType):[];var Ie=class e extends C{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.object)return m(t,{code:l.invalid_type,expected:s.object,received:t.parsedType}),g;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}):(m(t,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}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=N(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:U.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...S(r)})}};function Le(e,t){let n=c(e),r=c(t);if(e===t)return{valid:!0,data:e};if(n===s.object&&r===s.object){let n=a.objectKeys(t),r=a.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=Le(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===s.array&&r===s.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=Le(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===s.date&&r===s.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var Re=class extends C{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ne(e)||ne(r))return g;let i=Le(e.value,r.value);return i.valid?((re(e)||re(r))&&t.dirty(),{status:t.value,value:i.data}):(m(n,{code:l.invalid_intersection_types}),g)};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}))}};Re.create=(e,t,n)=>new Re({left:e,right:t,typeName:U.ZodIntersection,...S(n)});var P=class e extends C{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.array)return m(n,{code:l.invalid_type,expected:s.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return m(n,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),g;!this._def.rest&&n.data.length>this._def.items.length&&(m(n,{code:l.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 x(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>h.mergeArray(t,e)):h.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};P.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new P({items:e,typeName:U.ZodTuple,rest:null,...S(t)})};var ze=class e extends C{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!==s.object)return m(n,{code:l.invalid_type,expected:s.object,received:n.parsedType}),g;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new x(n,e,n.path,e)),value:a._parse(new x(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?h.mergeObjectAsync(t,r):h.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof C?new e({keyType:t,valueType:n,typeName:U.ZodRecord,...S(r)}):new e({keyType:w.create(),valueType:t,typeName:U.ZodRecord,...S(n)})}},Be=class extends C{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!==s.map)return m(n,{code:l.invalid_type,expected:s.map,received:n.parsedType}),g;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new x(n,e,n.path,[a,`key`])),value:i._parse(new x(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 g;(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 g;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};Be.create=(e,t,n)=>new Be({valueType:t,keyType:e,typeName:U.ZodMap,...S(n)});var Ve=class e extends C{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==s.set)return m(n,{code:l.invalid_type,expected:s.set,received:n.parsedType}),g;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(m(n,{code:l.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&&(m(n,{code:l.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 g;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 x(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)}};Ve.create=(e,t)=>new Ve({valueType:e,minSize:null,maxSize:null,typeName:U.ZodSet,...S(t)});var He=class e extends C{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==s.function)return m(t,{code:l.invalid_type,expected:s.function,received:t.parsedType}),g;function n(e,n){return ee({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,p(),d].filter(e=>!!e),issueData:{code:l.invalid_arguments,argumentsError:n}})}function r(e,n){return ee({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,p(),d].filter(e=>!!e),issueData:{code:l.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof R){let e=this;return _(async function(...t){let o=new u([]),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 _(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new u([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new u([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:P.create(t).rest(D.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||P.create([]).rest(D.create()),returns:n||D.create(),typeName:U.ZodFunction,...S(r)})}},F=class extends C{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})}};F.create=(e,t)=>new F({getter:e,typeName:U.ZodLazy,...S(t)});var I=class extends C{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return m(t,{received:t.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:`valid`,value:e.data}}get value(){return this._def.value}};I.create=(e,t)=>new I({value:e,typeName:U.ZodLiteral,...S(t)});function Ue(e,t){return new L({values:e,typeName:U.ZodEnum,...S(t)})}var L=class e extends C{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return m(t,{expected:a.joinValues(n),received:t.parsedType,code:l.invalid_type}),g}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return m(t,{received:t.data,code:l.invalid_enum_value,options:n}),g}return _(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})}};L.create=Ue;var We=class extends C{_parse(e){let t=a.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==s.string&&n.parsedType!==s.number){let e=a.objectValues(t);return m(n,{expected:a.joinValues(e),received:n.parsedType,code:l.invalid_type}),g}if(this._cache||=new Set(a.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=a.objectValues(t);return m(n,{received:n.data,code:l.invalid_enum_value,options:e}),g}return _(e.data)}get enum(){return this._def.values}};We.create=(e,t)=>new We({values:e,typeName:U.ZodNativeEnum,...S(t)});var R=class extends C{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==s.promise&&t.common.async===!1?(m(t,{code:l.invalid_type,expected:s.promise,received:t.parsedType}),g):_((t.parsedType===s.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};R.create=(e,t)=>new R({type:e,typeName:U.ZodPromise,...S(t)});var z=class extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===U.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=>{m(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 g;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?g:r.status===`dirty`||t.value===`dirty`?te(r.value):r});{if(t.value===`aborted`)return g;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?g:r.status===`dirty`||t.value===`dirty`?te(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`?g:(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`?g:(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(!v(e))return g;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=>v(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):g);a.assertNever(r)}};z.create=(e,t,n)=>new z({schema:e,typeName:U.ZodEffects,effect:t,...S(n)}),z.createWithPreprocess=(e,t,n)=>new z({schema:t,effect:{type:`preprocess`,transform:e},typeName:U.ZodEffects,...S(n)});var B=class extends C{_parse(e){return this._getType(e)===s.undefined?_(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};B.create=(e,t)=>new B({innerType:e,typeName:U.ZodOptional,...S(t)});var V=class extends C{_parse(e){return this._getType(e)===s.null?_(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};V.create=(e,t)=>new V({innerType:e,typeName:U.ZodNullable,...S(t)});var Ge=class extends C{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===s.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ge.create=(e,t)=>new Ge({innerType:e,typeName:U.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...S(t)});var H=class extends C{_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 y(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new u(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new u(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};H.create=(e,t)=>new H({innerType:e,typeName:U.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...S(t)});var Ke=class extends C{_parse(e){if(this._getType(e)!==s.nan){let t=this._getOrReturnCtx(e);return m(t,{code:l.invalid_type,expected:s.nan,received:t.parsedType}),g}return{status:`valid`,value:e.data}}};Ke.create=e=>new Ke({typeName:U.ZodNaN,...S(e)});var qe=class extends C{_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}},Je=class e extends C{_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`?g:e.status===`dirty`?(t.dirty(),te(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`?g: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:U.ZodPipeline})}},Ye=class extends C{_parse(e){let t=this._def.innerType._parse(e),n=e=>(v(e)&&(e.value=Object.freeze(e.value)),e);return y(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};Ye.create=(e,t)=>new Ye({innerType:e,typeName:U.ZodReadonly,...S(t)}),j.lazycreate;var U;(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`})(U||={});const W=w.create,G=ke.create;Ke.create,Ae.create;const K=je.create;Me.create,Ne.create,T.create,E.create,Pe.create,D.create,O.create,Fe.create;const q=k.create,J=j.create;j.strictCreate,M.create,Ie.create,Re.create,P.create;const Xe=ze.create;Be.create,Ve.create,He.create,F.create,I.create;const Y=L.create;We.create,R.create,z.create,B.create,V.create,z.createWithPreprocess,Je.create,J({modules:Xe(Y([`analytics`,`related-posts`,`link-monitor`,`editorial-polish`]),K()).default({analytics:!0,"related-posts":!0,"link-monitor":!1,"editorial-polish":!0}),analytics:J({retentionDays:G().int().min(7).max(365).default(90),excludePaths:q(W()).default([`/_emdash`])}).default({}),relatedPosts:J({maxResults:G().int().min(1).max(12).default(4),collections:q(W()).default([`posts`])}).default({})}),J({path:W().min(1).max(512),referrer:W().max(1024).optional(),utmSource:W().max(128).optional(),utmMedium:W().max(128).optional(),utmCampaign:W().max(128).optional(),contentId:W().max(128).optional()}),J({email:W().email().max(254),name:W().min(1).max(120).optional(),source:W().max(128).default(`website`),tags:q(W().max(48)).max(10).default([]),notes:W().max(2e3).optional(),website_url:W().max(512).optional()});const Ze=Y([`lead`,`qualified`,`customer`,`churned`]);J({email:W().email(),name:W().optional(),stage:Ze.default(`lead`),tags:q(W()).default([]),source:W(),createdAt:W(),updatedAt:W(),timeline:q(J({at:W(),type:Y([`created`,`form_submit`,`stage_change`,`note`,`newsletter_optin`]),summary:W()})).default([])});const Qe=J({email:W().email().max(254),listId:W().max(64).default(`default`),website_url:W().max(0).optional()}),$e=Y([`pending`,`confirmed`,`unsubscribed`]),et=J({email:W().email(),listId:W(),status:$e,confirmToken:W().optional(),unsubscribeToken:W(),createdAt:W(),updatedAt:W(),confirmedAt:W().optional()}),tt=J({digest:J({enabled:K().default(!1),collections:q(W()).default([`posts`]),listId:W().max(64).default(`default`),maxRecipients:G().int().min(1).max(100).default(50)}).default({})});J({collection:W(),id:W(),slug:W(),title:W(),termIds:q(W()).default([]),publishedAt:W().optional()}),J({dashcommerce:J({pluginId:W().min(1).max(64).default(`dashcommerce`),activeStatuses:q(W().min(1).max(32)).default([`active`,`trialing`,`past_due`])}).default({}),sessionTtlSeconds:G().int().min(300).max(3600*24*30).default(3600*24*7)}),J({token:W().min(16).max(512)});const nt=Y([`openai`,`anthropic`,`cloudflare_workers_ai`,`cloudflare_ai_gateway`,`google`]),rt=Y([`openai`,`workers-ai`,`google-ai-studio`]);J({enabled:K().default(!1),provider:nt.default(`openai`),defaultLocale:W().min(2).max(16).default(`en`),translationCollections:q(W()).default([`posts`,`pages`]),cloudflareAccountId:W().max(64).default(``),cloudflareWorkersAiModel:W().min(1).max(128).default(`@cf/meta/llama-3.1-8b-instruct`),cloudflareAiGatewayId:W().max(64).default(``),cloudflareAiGatewayUpstream:rt.default(`openai`),cloudflareAiGatewayModel:W().min(1).max(128).default(`gpt-4o-mini`),googleModel:W().min(1).max(128).default(`gemini-2.0-flash`)}),Y([`bluesky`,`mastodon`,`linkedin`,`x`]),J({enabled:K().default(!1),destinations:q(J({name:W().regex(/^[a-z0-9][a-z0-9_-]{0,31}$/),url:W().max(2048).refine(e=>{if(!URL.canParse(e))return!1;let t=new URL(e);return t.protocol===`https:`&&!t.username&&!t.password&&!t.hash})})).max(5).refine(e=>new Set(e.map(({name:e})=>e)).size===e.length).default([]),utmSource:W().max(64).default(`jetpack`),utmMedium:W().max(64).default(`social`),utmCampaign:W().max(64).default(`syndication`)}),J({id:W(),status:W(),currency:W().optional(),unitAmount:G().optional(),interval:W().optional(),intervalCount:G().optional(),currentPeriodEnd:G().optional(),cancelAtPeriodEnd:K().optional(),providerId:W().optional()});const it={coreConfig:()=>`cfg:core`,analyticsDailyRollup:(e,t)=>`ana:rollup:${e}:${t}`,relatedIndexEntry:(e,t)=>`rel:idx:${e}:${t}`,relatedCorpusMeta:()=>`rel:corpus_meta`,newsletterConfig:()=>`cfg:newsletter`,membershipsConfig:()=>`cfg:memberships`,membershipSession:e=>`mbr:session:${e}`,aiConfig:()=>`cfg:ai`,socialConfig:()=>`cfg:social`,socialQueueItem:e=>`social:queue:${e}`};function at(e,t){return{type:`header`,text:e,...t?.blockId!==void 0&&{block_id:t.blockId}}}function ot(e,t){return{type:`section`,text:e,...t?.accessory!==void 0&&{accessory:t.accessory},...t?.blockId!==void 0&&{block_id:t.blockId}}}function st(e){return{type:`divider`,...e?.blockId!==void 0&&{block_id:e.blockId}}}function ct(e,t){return{type:`fields`,fields:e,...t?.blockId!==void 0&&{block_id:t.blockId}}}function lt(e){return{type:`table`,columns:e.columns,rows:e.rows,page_action_id:e.pageActionId,...e.nextCursor!==void 0&&{next_cursor:e.nextCursor},...e.emptyText!==void 0&&{empty_text:e.emptyText},...e.blockId!==void 0&&{block_id:e.blockId}}}function ut(e,t){return{type:`actions`,elements:e,...t?.blockId!==void 0&&{block_id:t.blockId}}}function dt(e,t){return{type:`stats`,items:e,...t?.blockId!==void 0&&{block_id:t.blockId}}}function ft(e){return{type:`form`,fields:e.fields,submit:{label:e.submit.label,action_id:e.submit.actionId},...e.blockId!==void 0&&{block_id:e.blockId}}}function pt(e){return{type:`image`,url:e.url,alt:e.alt,...e.title!==void 0&&{title:e.title},...e.blockId!==void 0&&{block_id:e.blockId}}}function mt(e,t){return{type:`context`,text:e,...t?.blockId!==void 0&&{block_id:t.blockId}}}function ht(e,t){return{type:`columns`,columns:e,...t?.blockId!==void 0&&{block_id:t.blockId}}}function gt(e){return{type:`banner`,...e.title!==void 0&&{title:e.title},...e.description!==void 0&&{description:e.description},...e.variant!==void 0&&{variant:e.variant},...e.blockId!==void 0&&{block_id:e.blockId}}}function _t(e,t,n){return{type:`text_input`,action_id:e,label:t,...n?.placeholder!==void 0&&{placeholder:n.placeholder},...n?.initialValue!==void 0&&{initial_value:n.initialValue},...n?.multiline!==void 0&&{multiline:n.multiline}}}function vt(e,t,n){return{type:`link`,label:e,target:t,...n?.appearance!==void 0&&{appearance:n.appearance}}}function yt(e,t,n,r){return{type:`menu`,action_id:e,label:t,items:n,...r?.style!==void 0&&{style:r.style}}}function bt(e,t,n){return{type:`number_input`,action_id:e,label:t,...n?.initialValue!==void 0&&{initial_value:n.initialValue},...n?.min!==void 0&&{min:n.min},...n?.max!==void 0&&{max:n.max}}}function xt(e,t,n,r){return{type:`select`,action_id:e,label:t,options:n,...r?.initialValue!==void 0&&{initial_value:r.initialValue}}}function St(e,t,n){return{type:`toggle`,action_id:e,label:t,...n?.description!==void 0&&{description:n.description},...n?.initialValue!==void 0&&{initial_value:n.initialValue}}}function Ct(e,t,n){return{type:`button`,action_id:e,label:t,...n?.style!==void 0&&{style:n.style},...n?.value!==void 0&&{value:n.value},...n?.confirm!==void 0&&{confirm:n.confirm}}}function wt(e,t,n){return{type:`secret_input`,action_id:e,label:t,...n?.placeholder!==void 0&&{placeholder:n.placeholder},...n?.hasValue!==void 0&&{has_value:n.hasValue}}}function Tt(e,t,n,r){return{type:`checkbox`,action_id:e,label:t,options:n,...r?.initialValue!==void 0&&{initial_value:r.initialValue}}}function Et(e,t,n){return{type:`date_input`,action_id:e,label:t,...n?.initialValue!==void 0&&{initial_value:n.initialValue},...n?.placeholder!==void 0&&{placeholder:n.placeholder}}}function Dt(e,t,n,r){return{type:`combobox`,action_id:e,label:t,options:n,...r?.initialValue!==void 0&&{initial_value:r.initialValue},...r?.placeholder!==void 0&&{placeholder:r.placeholder}}}function Ot(e,t,n,r){return{type:`radio`,action_id:e,label:t,options:n,...r?.initialValue!==void 0&&{initial_value:r.initialValue}}}function kt(e,t,n,r){return{type:`repeater`,action_id:e,label:t,fields:n,...r?.itemLabel!==void 0&&{item_label:r.itemLabel},...r?.minItems!==void 0&&{min_items:r.minItems},...r?.maxItems!==void 0&&{max_items:r.maxItems},...r?.initialValue!==void 0&&{initial_value:r.initialValue}}}function At(e,t,n){return{type:`media_picker`,action_id:e,label:t,...n?.mimeTypeFilter!==void 0&&{mime_type_filter:n.mimeTypeFilter},...n?.initialValue!==void 0&&{initial_value:n.initialValue},...n?.placeholder!==void 0&&{placeholder:n.placeholder}}}function jt(e){return{type:`chart`,config:{chart_type:`timeseries`,series:e.series,...e.style!==void 0&&{style:e.style},...e.xAxisName!==void 0&&{x_axis_name:e.xAxisName},...e.yAxisName!==void 0&&{y_axis_name:e.yAxisName},...e.height!==void 0&&{height:e.height},...e.gradient!==void 0&&{gradient:e.gradient}},...e.blockId!==void 0&&{block_id:e.blockId}}}function Mt(e){return{type:`chart`,config:{chart_type:`custom`,options:e.options,...e.height!==void 0&&{height:e.height}},...e.blockId!==void 0&&{block_id:e.blockId}}}function Nt(e){return{type:`meter`,label:e.label,value:e.value,...e.max!==void 0&&{max:e.max},...e.min!==void 0&&{min:e.min},...e.customValue!==void 0&&{custom_value:e.customValue},...e.blockId!==void 0&&{block_id:e.blockId}}}function Pt(e){return{type:`code`,code:e.code,...e.language!==void 0&&{language:e.language},...e.blockId!==void 0&&{block_id:e.blockId}}}function Ft(e,t){return{type:`tab`,panels:e,...t?.defaultTab!==void 0&&{default_tab:t.defaultTab},...t?.blockId!==void 0&&{block_id:t.blockId}}}function It(e){return{type:`empty`,title:e.title,...e.description!==void 0&&{description:e.description},...e.commandLine!==void 0&&{command_line:e.commandLine},...e.size!==void 0&&{size:e.size},...e.actions!==void 0&&{actions:e.actions},...e.blockId!==void 0&&{block_id:e.blockId}}}function Lt(e){return{type:`accordion`,label:e.label,blocks:e.blocks,...e.defaultOpen!==void 0&&{default_open:e.defaultOpen},...e.blockId!==void 0&&{block_id:e.blockId}}}const X={header:at,section:ot,divider:st,fields:ct,table:lt,actions:ut,stats:dt,form:ft,image:pt,context:mt,columns:ht,timeseriesChart:jt,customChart:Mt,banner:gt,meter:Nt,code:Pt,tab:Ft,empty:It,accordion:Lt},Rt={textInput:_t,numberInput:bt,select:xt,toggle:St,button:Ct,link:vt,menu:yt,secretInput:wt,checkbox:Tt,combobox:Dt,dateInput:Et,radio:Ot,repeater:kt,mediaPicker:At};new TextEncoder;async function zt(e){let t=it.newsletterConfig(),n=await e.settings.get(t)??await e.kv.get(t),r=tt.safeParse(n??{});return r.success?r.data:tt.parse({})}async function Bt(e,t){await e.settings.set(it.newsletterConfig(),tt.parse(t))}const Vt=/^[a-f0-9]{48}$/;function Z(e){return e.storage.subscribers}function Ht(e,t,n,r){let i=e.url(`/_emdash/api/plugins/${e.plugin.id}/${t}`);return`${r?new URL(i,r).href:i}?${new URLSearchParams({token:n})}`}function Q(t){return e({status:303,headers:{Location:`/jetpack/newsletter?${new URLSearchParams(t)}`}})}function Ut(e){return t({public:!0,methods:[`GET`],request:{body:`none`},response:`raw`,handler:async({input:t})=>{let n=t.token;return typeof n==`string`&&Vt.test(n)?Q({action:e,token:n}):Q({result:`invalid`})}})}const Wt=t({public:!0,methods:[`POST`],request:{body:`form-data`,maxBytes:1024},response:`raw`,handler:async({input:e},t)=>{let n=e.entries.find(e=>e.name===`action`),r=e.entries.find(e=>e.name===`token`);if(n?.kind!==`text`||n.value!==`confirm`&&n.value!==`unsubscribe`||r?.kind!==`text`||!Vt.test(r.value))return Q({result:`invalid`});let i=n.value===`confirm`,a=i?`confirmToken`:`unsubscribeToken`,o=Z(t),{items:[s]}=await o.query({where:{[a]:r.value},limit:1});if(!s)return Q({result:`invalid`});for(let e=0;e<4;e++){let e=await o.getVersioned(s.id);if(!e)return Q({result:`invalid`});let t=et.safeParse(e.value);if(!t.success)return Q({result:`invalid`});let n=t.data;if(n[a]!==r.value||i&&n.status!==`pending`)return Q({result:`invalid`});if(!i&&n.status===`unsubscribed`)return Q({result:`unsubscribed`});let c=new Date().toISOString(),{confirmToken:l,...u}=n,d=i?`confirmed`:`unsubscribed`;if((await o.compareAndSet(s.id,e.revision,{...u,status:d,updatedAt:c,...i?{confirmedAt:c}:{}})).applied)return Q({result:d})}throw Error(`Subscription changed. Please try again.`)}}),$=`send-publish-digests`;function Gt(e){return e.storage.digest_jobs}async function Kt(e){let{items:t}=await Gt(e).query({orderBy:{createdAt:`desc`},limit:10});return t.map(({data:e})=>e)}async function qt(e){await e.cron?.schedule($,{schedule:`* * * * *`})}async function Jt(e,t){let{digest:n}=await zt(e),{collection:i,content:a}=t;if(!n.enabled||!n.collections.includes(i)||typeof a.id!=`string`||!a.id)return;e.cron&&!(await e.cron.list()).some(({name:e})=>e===$)&&await qt(e);let{items:o}=await Z(e).query({where:{status:`confirmed`,listId:n.listId},limit:n.maxRecipients});if(o.length===0)return;let s=a.data?.title??a.title,c=await r(JSON.stringify([i,a.id,a.publishedAt??null,a.version??null]));await Gt(e).compareAndSet(c,null,{collection:i,entryId:a.id,title:typeof s==`string`?s:`New post`,listId:n.listId,createdAt:new Date().toISOString(),status:`queued`,claimedUntil:0,pending:o.map(({id:e})=>({id:e,attempts:0})),inFlight:null,sent:0,failed:0,skipped:0,uncertain:0})}async function Yt(e){let{email:t,content:n}=e;if(!t||!n?.getPublicUrl||!(await zt(e)).digest.enabled)return;let r=Gt(e),i=Date.now(),{items:[a]}=await r.query({where:{status:`queued`,claimedUntil:{lte:i}},orderBy:{createdAt:`asc`},limit:1});if(!a)return;let{id:o}=a,s=await r.getVersioned(o);if(!s||s.value.status!==`queued`||s.value.claimedUntil>i)return;let c=s.value;c.claimedUntil=i+12e4;let l=await r.compareAndSet(o,s.revision,c);if(!l.applied)return;let u=l.revision;async function d(){let e=await r.compareAndSet(o,u,c);if(!e.applied)throw Error(`Newsletter digest batch claim changed.`);u=e.revision}c.inFlight&&(c.uncertain+=1,c.inFlight=null,await d());let f=await n.getPublicUrl(c.collection,c.entryId);f||(c.skipped+=c.pending.length,c.pending=[]);let p=c.pending.slice(0,5);for(let n of p){let r=et.safeParse(await Z(e).get(n.id));if(c.pending.shift(),!f||!r.success||r.data.status!==`confirmed`||r.data.listId!==c.listId){c.skipped+=1,await d();continue}let i=e.site.name||`this site`,a=Ht(e,`unsubscribe`,r.data.unsubscribeToken,URL.canParse(f)?f:void 0),o={to:r.data.email,subject:`New on ${i}: ${c.title}`,text:`${i} published: ${c.title}\n\n${f}\n\nUnsubscribe: ${a}\n`};n.attempts+=1,c.inFlight=n,await d();try{await t.send(o),c.sent+=1}catch{n.attempts<3?c.pending.push(n):c.failed+=1}c.inFlight=null,await d()}c.claimedUntil=0,c.pending.length===0&&(c.status=`completed`),await d(),c.status===`completed`&&(c.failed||c.uncertain)&&e.log.warn(`Newsletter digest completed with delivery issues`,{collection:c.collection,entryId:c.entryId,sent:c.sent,failed:c.failed,uncertain:c.uncertain})}async function Xt(e,t){let n=Z(e),[r,i,a,o]=await Promise.all([n.count({status:`confirmed`}),n.count({status:`pending`}),n.count({status:`unsubscribed`}),Kt(e)]),s=r+i+a;return{blocks:[X.header(`Newsletter`),X.context(`Subscribers: ${s}. Confirmed: ${r} · Pending: ${i} · Unsubscribed: ${a}.`),X.context(`Publish digest queues emails for confirmed subscribers on the "${t.digest.listId}" list when a post is published in: ${t.digest.collections.join(`, `)}.`),X.header(`Recent digest deliveries`),...o.length===0?[X.context(`No digest jobs yet.`)]:[],...o.map(e=>X.context(`${e.title.slice(0,120)} · Pending: ${e.pending.length+Number(!!e.inFlight)} · Delivered: ${e.sent} · Failed: ${e.failed} · Uncertain: ${e.uncertain} · Skipped: ${e.skipped}`)),X.form({blockId:`newsletter-settings`,fields:[Rt.toggle(`digest:enabled`,`Queue digest email on publish`,{initialValue:t.digest.enabled})],submit:{label:`Save newsletter settings`,actionId:`save-newsletter`}})]}}const Zt=t({methods:[`POST`],request:{body:`json`},handler:async(e,t)=>{let n=e.input;if(n.type===`form_submit`&&n.action_id===`save-newsletter`){let e=await zt(t),r=`digest:enabled`,i=r in n.values?!!n.values[r]:e.digest.enabled,a=tt.parse({...e,digest:{...e.digest,enabled:i}});return await Bt(t,a),{...await Xt(t,a),toast:{message:`Newsletter settings saved`,type:`success`}}}return Xt(t,await zt(t))}}),Qt={hooks:{"plugin:activate":(e,t)=>qt(t),"plugin:deactivate":async(e,t)=>{await t.cron?.cancel($)},"content:afterPublish":(e,t)=>Jt(t,e),cron:async({name:e},t)=>{e===$&&await Yt(t)}},routes:{admin:Zt,subscribe:t({public:!0,methods:[`POST`],request:{body:`json`,maxBytes:2048},handler:async({input:e,request:t},n)=>{let a=Qe.safeParse(e);if(!a.success)return{ok:!1,error:`invalid_payload`};if(!n.email)return{ok:!1,error:`email_unavailable`};let o=a.data.email.toLowerCase(),s=Z(n),{items:[c]}=await s.query({where:{email:o},limit:1}),l=c?.id??await r(o),u=i(),d=Ht(n,`confirm`,u,t.url);for(let e=0;e<4;e++){let e=await s.getVersioned(l),t=e&&et.parse(e.value);if(t&&t.listId!==a.data.listId)return{ok:!1,error:`list_mismatch`};if(t?.status===`confirmed`)return{ok:!0,status:`confirmed`};let r=new Date().toISOString(),c=et.parse({...t??{email:o,listId:a.data.listId,unsubscribeToken:i(),createdAt:r},status:`pending`,...t?.status===`unsubscribed`&&{unsubscribeToken:i()},confirmToken:u,updatedAt:r});if(!(await s.compareAndSet(l,e?.revision??null,c)).applied)continue;let f=n.site.name||`this site`;return await n.email.send({to:o,subject:`Confirm your subscription to ${f}`,text:`Open this link to confirm your subscription:\n\n${d}\n\nIf you did not request this, ignore this email.`}),{ok:!0,status:`pending`}}throw Error(`Subscription changed. Please try again.`)}}),confirm:Ut(`confirm`),unsubscribe:Ut(`unsubscribe`),"subscription-action":Wt,health:{handler:async(e,t)=>({ok:!0,pluginId:t.plugin.id})}}};export{Qt as default};
@@ -0,0 +1,44 @@
1
+ {
2
+ "$schema": "../../node_modules/@emdash-cms/plugin-cli/schemas/emdash-plugin.schema.json",
3
+
4
+ "slug": "emdashjetpack-newsletter",
5
+ "publisher": "did:plc:ldzgvxqlbij5imfwfhbsxyou",
6
+
7
+ "license": "MIT",
8
+ "author": { "name": "Alexander Asomba" },
9
+ "security": { "email": "alex@theworkflow.dev" },
10
+ "repo": "https://github.com/emdashJetpack/emdashjetpack",
11
+ "release": {
12
+ "artifacts": {
13
+ "icon": { "file": "./assets/jetpack-icon.png" },
14
+ },
15
+ },
16
+
17
+ "name": "EmDash Jetpack Newsletter",
18
+ "description": "Collect confirmed newsletter subscriptions and send optional publish digests through your site's EmDash email provider.",
19
+ "sections": {
20
+ "description": "Readers confirm their subscriptions by email. When publish digests are enabled, Newsletter queues a message with the new post's link for confirmed subscribers on the digest list. Each digest includes an unsubscribe link. Review delivery counts in Newsletter admin.",
21
+ "installation": "Configure your site's EmDash email provider, then install and activate Newsletter. Use the Jetpack Astro companion to add the signup form and confirmation page. Subscribe with a test address and confirm from the email. On a test site, enable Queue digest email on publish, publish a post, and use the delivered digest to test unsubscribe. See the setup guide at https://github.com/emdashJetpack/emdashjetpack/tree/main/packages/newsletter#setup.",
22
+ "security": "Newsletter reads published content to build digest links and sends mail through your site's configured EmDash email provider. It stores subscriber addresses, list IDs, subscription status, confirmation and unsubscribe tokens, and digest delivery state in plugin storage. Newsletter keeps the subscriber record when a reader unsubscribes so the subscription status is preserved.",
23
+ },
24
+
25
+ "capabilities": ["email:send", "content:read"],
26
+ "allowedHosts": [],
27
+ "storage": {
28
+ "digest_jobs": { "indexes": ["status", "createdAt", "claimedUntil"] },
29
+ "subscribers": {
30
+ "indexes": ["email", "listId", "status", "updatedAt", "confirmToken", "unsubscribeToken"],
31
+ "uniqueIndexes": ["email"],
32
+ },
33
+ },
34
+
35
+ "admin": {
36
+ "pages": [
37
+ {
38
+ "path": "/newsletter",
39
+ "label": "Newsletter",
40
+ "icon": "mail",
41
+ },
42
+ ],
43
+ },
44
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@emdashjetpack/newsletter",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.5.2",
4
+ "description": "Double opt-in subscriptions and publish digests for EmDash.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/emdashJetpack/emdashjetpack.git",
9
+ "directory": "packages/newsletter"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "emdash-plugin.jsonc"
14
+ ],
15
+ "type": "module",
16
+ "main": "dist/index.mjs",
17
+ "exports": {
18
+ ".": {
19
+ "import": "./dist/index.mjs",
20
+ "types": "./dist/index.d.mts"
21
+ },
22
+ "./sandbox": "./dist/plugin.mjs"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "dependencies": {
28
+ "@emdash-cms/blocks": "1.7.0"
29
+ },
30
+ "peerDependencies": {
31
+ "emdash": "^1.6.0"
32
+ },
33
+ "scripts": {
34
+ "validate": "emdash-plugin validate",
35
+ "build": "emdash-plugin build",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "emdash-plugin validate && vp test run"
38
+ }
6
39
  }