@xpoudy/free-tools 0.1.1 → 1.1.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.
@@ -0,0 +1,133 @@
1
+ import {modelResult,requiredText,emailFormat,csvDownload,asciiDomain} from './common.js';
2
+ import {column,spreadsheet,tabular,check,count,list,key,file,columnRows} from './toolbox-data.js';
3
+ import {parsePhoneNumberFromString,getDomain} from './toolbox-vendor-data.js';
4
+ import {disposableDomains} from './toolbox-disposable.js';
5
+ const nameForm=x=>String(x??'').normalize('NFKD').replace(/\p{M}/gu,'').toLowerCase().replace(/[^a-z0-9]/g,'');
6
+ export function extractor(v){
7
+ const text=requiredText(v.source,'text containing email addresses');
8
+ const hits=text.match(/[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[\p{L}\p{N}.-]+\.[\p{L}\p{N}-]{2,63}/giu)??[];
9
+ check(hits.length<=50000,'Use 50,000 candidate addresses or fewer.');
10
+ const unique=new Map();
11
+ let valid=0;
12
+ for(const raw of hits){const verdict=emailFormat(raw);if(verdict.status==='Format looks valid'){valid++;if(!unique.has(verdict.key))unique.set(verdict.key,raw);}}
13
+ return tabular([['Unique addresses',count(unique.size)],['Repeat occurrences',count(valid-unique.size)]],['Email address'],[...unique.values()].map(x=>[x]),'extracted-emails.csv',['The first matching spelling is kept. The result only confirms that the address appears in the supplied text and looks syntactically valid.']);
14
+ }
15
+ export function permutator(v){
16
+ const first=nameForm(v.first),last=nameForm(v.last),domain=asciiDomain(v.domain);
17
+ check(first&&last&&first.length+last.length<=55,'Enter a first and last name with usable Latin letters.');
18
+ check(domain,'Enter a valid company domain.');
19
+ const forms=[[first,'first'],[first+'.'+last,'first.last'],[first+last,'firstlast'],[first[0]+last,'flast'],[first+'_'+last,'first_last'],[first+'-'+last,'first-last'],[last+'.'+first,'last.first'],[last+first[0],'lastf'],[first+last[0],'firstl'],[last,'last']];
20
+ const unique=new Map();for(const [suggestion,pattern] of forms)if(!unique.has(suggestion))unique.set(suggestion,pattern);
21
+ const rows=[...unique].map(([suggestion,pattern])=>[suggestion+'@'+domain,pattern,'Unverified']);
22
+ return tabular([['Possible addresses',count(rows.length)]],['Address','Pattern','Verification'],rows,'address-patterns.csv',['A pattern is a guess. Verify the address through an appropriate source before relying on it.']);
23
+ }
24
+ const knownTypo=new Map([['gmial.com','gmail.com'],['gmal.com','gmail.com'],['gmai.com','gmail.com'],['gmail.con','gmail.com'],['hotmial.com','hotmail.com'],['outlok.com','outlook.com'],['yaho.com','yahoo.com'],['yahoo.con','yahoo.com'],['outlook.con','outlook.com'],['gamil.com','gmail.com']]);
25
+ export function domainTypos(v){
26
+ const {data,index}=columnRows(v.csv,v.email_column);
27
+ const extra=new Map();
28
+ for(const item of list(v.rules)){
29
+ const [from,to,...unused]=item.split('=');
30
+ const a=asciiDomain(from),b=asciiDomain(to);
31
+ check(a&&b&&!unused.length,'Write custom rules as old-domain=new-domain.');extra.set(a,b);
32
+ }
33
+ const rows=[];
34
+ for(const values of data.rows){const input=values[index].trim();const at=input.lastIndexOf('@');if(at<1)continue;const domain=key(input.slice(at+1));const replacement=extra.get(domain)??knownTypo.get(domain);if(replacement&&replacement!==domain)rows.push([input,input.slice(0,at+1)+replacement,'Review']);}
35
+ return tabular([['Rows inspected',count(data.rows.length)],['Suggestions',count(rows.length)]],['Supplied email','Suggested address','Decision'],rows,'review-address-corrections.csv',['Review the suggestions. The input file is never modified.']);
36
+ }
37
+ export function disposable(v){
38
+ const raw=list(requiredText(v.addresses,'email addresses or domains'));
39
+ check(raw.length<=25000,'Enter at most 25,000 addresses or domains.');
40
+ const checked=raw.map(input=>{
41
+ const domain=asciiDomain(input.split('@').at(-1));
42
+ return [input,domain??'—',domain?(disposableDomains.includes(domain)?'Listed as disposable':'Not found in bundled list'):'Invalid domain'];
43
+ });
44
+ return tabular([['Inputs',count(checked.length)],['Listed',count(checked.filter(r=>r[2]==='Listed as disposable').length)]],['Input','Domain','Result'],checked,'disposable-domain-check.csv',['The bundled list is a snapshot. An unfamiliar domain can still be a disposable service. Legitimate alias services may be handled separately.']);
45
+ }
46
+ const roles=new Set(['admin','abuse','billing','careers','contact','help','hello','hr','info','jobs','legal','marketing','noreply','no-reply','office','partners','postmaster','press','privacy','sales','security','support','team','webmaster']);
47
+ export function roleAddresses(v){
48
+ const {data,index}=columnRows(v.csv,v.email_column);
49
+ const custom=list(v.extra).map(key);
50
+ const targets=new Set([...roles,...custom]);
51
+ const rows=data.rows.map(row=>{const value=row[index].trim();const at=value.lastIndexOf('@');const local=key(value.slice(0,at)).split('+')[0];return [...row,at<1?'Review address':targets.has(local)?'Role address':'Not flagged'];});
52
+ return tabular([['Rows',count(rows.length)],['Role addresses',count(rows.filter(x=>x.at(-1)==='Role address').length)]],[...data.columns,'Role check'],rows,'review-role-addresses.csv',['A role mailbox can be appropriate for some contacts. Label these addresses for review rather than deleting them automatically.']);
53
+ }
54
+ export function segments(v){
55
+ const {columns,rows}=spreadsheet(v.csv);
56
+ const index=column(columns,v.segment_column), filter=v.filter_column?column(columns,v.filter_column):-1;
57
+ const groups=new Map();
58
+ const selected=rows.filter(r=>filter<0||key(r[filter]).includes(key(v.filter_value)));
59
+ for(const row of selected){const group=row[index].trim()||'Unspecified';const prev=groups.get(key(group))??{name:group,rows:[]};prev.rows.push([...row,prev.name]);groups.set(key(group),prev);}
60
+ check(groups.size<=2500,'Choose a column with no more than 2,500 values.');
61
+ const top=[...groups.values()].sort((a,b)=>b.rows.length-a.rows.length);
62
+ const downloads=[csvDownload('all-segmented-leads.csv',[...columns,'Segment'],top.flatMap(x=>x.rows))];
63
+ if(top.length<=25)for(const [i,item] of top.entries())downloads.push(csvDownload('segment-'+(i+1)+'.csv',[...columns,'Segment'],item.rows));
64
+ const summary=top.map((x,i)=>[x.name,x.rows.length,top.length<=25?'segment-'+(i+1)+'.csv':'Combined export']);
65
+ return modelResult([['Matching contacts',count(selected.length)],['Segments',count(top.length)]],{table:{columns:['Segment','Contacts','Download'],rows:summary.slice(0,100),total:summary.length},downloads});
66
+ }
67
+ const families=[[/sales|business development|account executive|revenue/i,'Sales and growth'],[/marketing|demand gen|brand|communications/i,'Marketing'],[/engineer|developer|technical|software|devops|\bcto\b/i,'Engineering'],[/human resources|talent|\bpeople\b|\bhr\b/i,'People'],[/finance|accountant|\bcfo\b/i,'Finance'],[/support|success|service/i,'Customer operations'],[/product|design/i,'Product and design'],[/operations|chief operating|\bcoo\b/i,'Operations']];
68
+ function titleInfo(input){
69
+ const text=String(input??'').trim();
70
+ if(!text)return ['Unspecified','Unspecified'];
71
+ const family=families.find(x=>x[0].test(text))?.[1]??'Review';
72
+ const seniority=/\b(?:chief|ceo|cfo|cto|coo|owner|founder)\b/i.test(text)?'Executive':/\b(?:vp|vice president|director|head)\b/i.test(text)?'Leadership':/\b(?:manager|supervisor)\b/i.test(text)?'Manager':/\b(?:senior|sr\.?|lead|principal)\b/i.test(text)?'Senior':/\b(?:junior|jr\.?|assistant|intern)\b/i.test(text)?'Entry / assistant':'Unspecified';
73
+ return [family,seniority];
74
+ }
75
+ export function titles(v){
76
+ const {data,index}=columnRows(v.csv,v.title_column);
77
+ const rows=data.rows.map(r=>[...r,...titleInfo(r[index])]);
78
+ return tabular([['Titles reviewed',count(rows.length)],['Unclassified roles',count(rows.filter(r=>r.at(-2)==='Review').length)]],[...data.columns,'Role family','Seniority'],rows,'normalized-job-titles.csv',['The tool uses rules, not enrichment or individual profiles. Review ambiguous and multilingual titles before using the labels.']);
79
+ }
80
+ export function phoneFormat(v){
81
+ const numbers=requiredText(v.phones,'phone numbers').split(/\r?\n/).map(x=>x.trim()).filter(Boolean);
82
+ check(numbers.length<=25000,'Use up to 25,000 phone numbers.');
83
+ const country=String(v.country??'').toUpperCase().trim();
84
+ check(!country||/^[A-Z]{2}$/.test(country),'Enter a two-letter country code such as US, GB, or MY.');
85
+ const rows=numbers.map(input=>{
86
+ const parsed=parsePhoneNumberFromString(input,{defaultCountry:country||undefined,extract:false});
87
+ return [input,parsed?.number??'',parsed?.ext??'',parsed?.country??'',parsed?.isValid()?'Fits numbering plan':'Review number'];
88
+ });
89
+ return tabular([['Numbers',count(rows.length)],['Need review',count(rows.filter(x=>x[4]!=='Fits numbering plan').length)]],['Input','E.164','Extension','Country','Status'],rows,'formatted-phones.csv',['Numbers are checked against public numbering-plan rules. No call or identity verification is performed.']);
90
+ }
91
+ function siteDomain(value){
92
+ const raw=String(value??'').trim();
93
+ if(!raw||/\s/.test(raw))return null;
94
+ try{const url=new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)?raw:'https://'+raw);if(!['http:','https:'].includes(url.protocol)||url.username||url.password)return null;return getDomain(url.hostname,{allowPrivateDomains:true});}catch{return null;}
95
+ }
96
+ export function domains(v){
97
+ const {data,index}=columnRows(v.csv,v.url_column);
98
+ const rows=data.rows.map(r=>[...r,siteDomain(r[index])??'']);
99
+ return tabular([['Rows processed',count(rows.length)],['Domains extracted',count(rows.filter(r=>r.at(-1)).length)]],[...data.columns,'Company domain'],rows,'company-domains.csv',['Hostname processing uses a public suffix snapshot. No website is visited.']);
100
+ }
101
+ const accountKey=value=>String(value??'').normalize('NFKD').replace(/\p{M}/gu,'').toLowerCase().replace(/\b(?:inc|corp|ltd|llc|gmbh|limited|plc|company|co)\b/g,'').replace(/[^a-z0-9]/g,'');
102
+ export function accounts(v){
103
+ const left=spreadsheet(v.leads),right=spreadsheet(v.accounts);
104
+ const ln=column(left.columns,v.lead_name),rn=column(right.columns,v.account_name);
105
+ const ld=v.lead_domain?column(left.columns,v.lead_domain):-1,rd=v.account_domain?column(right.columns,v.account_domain):-1;
106
+ const lookupName=new Map(),lookupDomain=new Map();
107
+ const add=(map,k,i)=>{if(k)map.set(k,[...(map.get(k)??[]),i]);};
108
+ for(const [i,r] of right.rows.entries()){add(lookupName,accountKey(r[rn]),i);if(rd>=0)add(lookupDomain,siteDomain(r[rd]),i);}
109
+ const rows=left.rows.map(r=>{
110
+ const matched=ld>=0?lookupDomain.get(siteDomain(r[ld])):null;
111
+ const name=lookupName.get(accountKey(r[ln]));
112
+ const candidates=matched?.length?matched:name??[];
113
+ return [...r,candidates.length===1?right.rows[candidates[0]][rn]:'',candidates.length>1?'Ambiguous match':candidates.length?matched?.length?'Domain match':'Normalized name match':'No match'];
114
+ });
115
+ return tabular([['Leads',count(rows.length)],['Single matches',count(rows.filter(x=>x.at(-2)).length)]],[...left.columns,'Suggested account','Match reason'],rows,'lead-account-matches.csv',['The matcher uses canonical domains first and normalized names second. Review ambiguous and name-only matches.']);
116
+ }
117
+ const escapeCard=value=>String(value??'').replace(/\\/g,'\\\\').replace(/\r?\n/g,'\\n').replace(/([,;])/g,'\\$1');
118
+ function foldCard(line){
119
+ const utf8=new TextEncoder();let part='',size=0;const out=[];
120
+ for(const char of line){const n=utf8.encode(char).length;if(size+n>75){out.push(part);part=' ';size=1;}part+=char;size+=n;}
121
+ out.push(part);return out.join('\r\n');
122
+ }
123
+ export function vcard(v){
124
+ const {columns,rows}=spreadsheet(v.csv);
125
+ const map=[v.name_column,v.email_column,v.phone_column,v.company_column].map(x=>x?column(columns,x):-1);
126
+ check(map[0]>=0,'Map a name column.');
127
+ const names=rows.filter(x=>String(x[map[0]]??'').trim());
128
+ const cards=names.map(r=>{
129
+ const [name,email,tel,org]=map.map(i=>i<0?'':escapeCard(r[i]));
130
+ return ['BEGIN:VCARD','VERSION:3.0','N:'+name+';;;;','FN:'+name,email?'EMAIL:'+email:'',tel?'TEL:'+tel:'',org?'ORG:'+org:'','END:VCARD'].filter(Boolean).map(foldCard).join('\r\n');
131
+ });
132
+ return modelResult([['Cards generated',count(cards.length)],['Rows without names',count(rows.length-cards.length)]],{downloads:[file('contacts.vcf',cards.join('\r\n')+'\r\n','text/vcard;charset=utf-8')]});
133
+ }
@@ -0,0 +1,153 @@
1
+ import {InputError,modelResult,requiredText,emailFormat,showNumber} from './common.js';
2
+ import {integer,numeric,check,tabular,spreadsheet,column,brief,file,count,toRatio} from './toolbox-data.js';
3
+ import {safeHttp} from './toolbox-compose.js';
4
+ const keys=['utm_source','utm_medium','utm_campaign','utm_term','utm_content','utm_id'];
5
+ export function utm(v){
6
+ const {columns,rows}=spreadsheet(v.csv);
7
+ const index=column(columns,v.url_column), optional=k=>columns.findIndex(c=>c.toLowerCase()===k);
8
+ const mapping=keys.map(optional);
9
+ const output=rows.map(r=>{
10
+ try{
11
+ const url=safeHttp(r[index]);
12
+ const value=k=>String(r[mapping[k]]||v[keys[k]]||url.searchParams.get(keys[k])||'').trim();
13
+ check(value(0)&&value(1)&&(value(2)||value(5)),'Supply a source, medium, and campaign name or ID.');
14
+ for(const [i,key] of keys.entries()){const val=value(i);if(val)url.searchParams.set(key,val);}
15
+ check(url.href.length<=8000,'The generated URL is too long.');
16
+ return [...r,url.href,'Ready'];
17
+ }catch(error){return [...r,'',error.message];}
18
+ });
19
+ return tabular([['Links created',count(output.filter(x=>x.at(-1)==='Ready').length)],['Rows need review',count(output.filter(x=>x.at(-1)!=='Ready').length)]],[...columns,'Campaign URL','Status'],output,'campaign-urls.csv',['Existing non-UTM parameters and fragments are retained. A row-level UTM field overrides the defaults.']);
20
+ }
21
+ function suppliedLinks(source){
22
+ if(/<a\b/i.test(source)){
23
+ const template=document.createElement('template');template.innerHTML=source;
24
+ return [...template.content.querySelectorAll('a[href]')].map(e=>[e.getAttribute('href'),e.textContent.trim()]);
25
+ }
26
+ return (source.match(/https?:\/\/[^\s<>"']+/gi)??[]).map(url=>[url.replace(/[.,;]+$/,''),'']);
27
+ }
28
+ export function linkAudit(v){
29
+ const source=requiredText(v.source,'links or email HTML',400000);
30
+ const entries=suppliedLinks(source);
31
+ check(entries.length>0&&entries.length<=2500,'Supply 1 to 2,500 links.');
32
+ const reports=[];
33
+ const patterns=new Map();
34
+ for(const [raw,text] of entries){
35
+ if(/^mailto:|^#/i.test(raw))continue;
36
+ try{
37
+ const url=safeHttp(raw);
38
+ const findings=[];
39
+ const tags=[...url.searchParams.keys()].filter(x=>/^utm_/i.test(x));
40
+ if(tags.length){
41
+ for(const key of new Set(tags)){
42
+ if(key!==key.toLowerCase())findings.push('Use lowercase parameter '+key);
43
+ if(url.searchParams.getAll(key).length>1)findings.push('Repeated '+key);
44
+ }
45
+ for(const param of ['utm_source','utm_medium'])if(!url.searchParams.get(param))findings.push('Missing '+param);
46
+ if(!url.searchParams.get('utm_campaign')&&!url.searchParams.get('utm_id'))findings.push('Missing campaign name or ID');
47
+ const medium=url.searchParams.get('utm_medium');if(medium)patterns.set(medium.toLowerCase(),new Set([...(patterns.get(medium.toLowerCase())??[]),medium]));
48
+ }
49
+ if(/^https?:\/\//i.test(text)){try{if(safeHttp(text).hostname!==url.hostname)findings.push('Visible URL and destination domains differ');}catch{findings.push('Visible URL could not be parsed');}}
50
+ reports.push([url.href,findings.join(' · ')||'No issue found']);
51
+ }catch{reports.push([raw,'Review malformed or unsupported URL']);}
52
+ }
53
+ const mixed=[...patterns.values()].filter(x=>x.size>1).map(x=>[...x].join(' / '));
54
+ return tabular([['Web links reviewed',count(reports.length)],['Links with findings',count(reports.filter(x=>x[1]!=='No issue found').length)]],['Destination','Finding'],reports,'campaign-link-audit.csv',[...(mixed.length?['Campaign medium case is inconsistent: '+mixed.join(', ')+'.']:[]),'The audit reads link structure. It does not visit the destination or measure clicks.']);
55
+ }
56
+ export function mailto(v){
57
+ const addresses=requiredText(v.to,'one or more recipient email addresses',2000).split(',').map(x=>x.trim());
58
+ const valid=x=>emailFormat(x).status==='Format looks valid'&&!/[?#%]/.test(x);
59
+ check(addresses.every(valid),'Enter valid email addresses separated by commas.');
60
+ const cc=String(v.cc??'').split(',').map(x=>x.trim()).filter(Boolean);
61
+ check(cc.every(valid),'Enter valid CC addresses separated by commas.');
62
+ check(!/[\r\n]/.test(v.subject??''),'Use one line for the subject.');
63
+ const pairs=[];
64
+ if(cc.length)pairs.push('cc='+cc.map(encodeURIComponent).join(','));
65
+ if(v.subject)pairs.push('subject='+encodeURIComponent(v.subject));
66
+ if(v.body)pairs.push('body='+encodeURIComponent(String(v.body).replace(/\r?\n/g,'\r\n')));
67
+ const output='mailto:'+addresses.map(x=>encodeURIComponent(x).replace('%40','@')).join(',')+(pairs.length?'?'+pairs.join('&'):'');
68
+ check(output.length<=16000,'Keep the email link to 16,000 characters or fewer.');
69
+ return modelResult([['Recipients',count(addresses.length)],['Link length',count(output.length)]],{text:output,downloads:[file('mailto-link.txt',output)],notes:['The link opens the visitor’s configured email app. Very long links can be shortened by the app or browser.']});
70
+ }
71
+ function toBlob(canvas,type,quality){return new Promise((resolve,reject)=>canvas.toBlob(v=>v?resolve(v):reject(new InputError('The browser could not export this image.')),type,quality));}
72
+ function exampleBitmap(){
73
+ const canvas=document.createElement('canvas');canvas.width=1400;canvas.height=800;
74
+ const ctx=canvas.getContext('2d');const grad=ctx.createLinearGradient(0,0,1400,800);grad.addColorStop(0,'#113654');grad.addColorStop(1,'#026856');ctx.fillStyle=grad;ctx.fillRect(0,0,1400,800);ctx.fillStyle='white';ctx.font='84px sans-serif';ctx.fillText('Email image sample',96,425);
75
+ return canvas;
76
+ }
77
+ export async function imageCompress(v,{files={},example=false}={}){
78
+ const upload=files.image?.[0];
79
+ check(upload||example,'Open a PNG, JPEG, or WebP image to compress.');
80
+ if(upload)check(upload.size<=8e6&&/\.(png|jpe?g|webp)$/i.test(upload.name),'Use a PNG, JPEG, or WebP image smaller than 8 MB.');
81
+ let bitmap;
82
+ try{bitmap=upload?await createImageBitmap(upload):exampleBitmap();}
83
+ catch{throw new InputError('The image could not be decoded. Try a different file.');}
84
+ try{
85
+ check(bitmap.width*bitmap.height<=25e6,'Choose an image with no more than 25 million pixels.');
86
+ const width=integer(v,'max_width',64,2400), limit=integer(v,'target_kb',8,1500)*1000;
87
+ const target=Math.min(width,bitmap.width);
88
+ const canvas=document.createElement('canvas');canvas.width=target;canvas.height=Math.max(1,Math.round(bitmap.height*target/bitmap.width));
89
+ const ctx=canvas.getContext('2d');ctx.fillStyle='white';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.drawImage(bitmap,0,0,canvas.width,canvas.height);
90
+ let blob;
91
+ for(const quality of [.9,.76,.6,.44,.28,.16]){blob=await toBlob(canvas,'image/jpeg',quality);if(blob.size<=limit)break;}
92
+ const original=upload?.size??(await toBlob(bitmap,'image/png')).size;
93
+ return modelResult([['Original',showNumber(original/1000)+' KB'],['Compressed',showNumber(blob.size/1000)+' KB'],['Target',blob.size<=limit?'Reached':'Above target'],['Dimensions',`${canvas.width} × ${canvas.height}`]],{downloads:[{name:'email-image.jpg',type:'image/jpeg',text:blob}],notes:['JPEG uses a white background for transparent areas. If the file remains above target, reduce the maximum width and rerun.']});
94
+ }finally{bitmap.close?.();}
95
+ }
96
+ export function engagement(v){
97
+ const delivered=integer(v,'delivered'),opened=integer(v,'unique_opens'),clicked=integer(v,'unique_clicks');
98
+ check(opened<=delivered&&clicked<=delivered,'Unique opens and clicks must each be at most delivered.');
99
+ return modelResult([['Open rate',toRatio(opened,delivered)],['Click rate',toRatio(clicked,delivered)],['Click-to-open rate',toRatio(clicked,opened)]],{notes:['Use unique counts from the same send. Image prefetching and automatic scans can affect open and click data.']});
100
+ }
101
+ export function funnel(v){
102
+ const values=['positive_replies','booked_meetings','held_meetings','sales'].map(k=>integer(v,k));
103
+ check(values.every((x,i)=>i===0||x<=values[i-1]),'Each stage must include no more contacts than the previous stage for the same cohort.');
104
+ const rows=['Positive replies','Booked meetings','Held meetings','Sales'].map((name,i)=>[name,values[i],i?toRatio(values[i],values[i-1]):'Starting count',i?values[i-1]-values[i]:'—']);
105
+ return tabular([['Reply-to-sale conversion',toRatio(values[3],values[0])],['Sales',count(values[3])]],['Stage','Contacts','Conversion from prior stage','Contacts lost'],rows,'outreach-funnel.csv');
106
+ }
107
+ export function complaints(v){
108
+ const delivered=integer(v,'delivered'),reported=integer(v,'complaints'),optOut=integer(v,'unsubscribes');
109
+ check(reported<=delivered&&optOut<=delivered,'Complaints and unsubscribes must each be at most delivered.');
110
+ return modelResult([['Complaint rate',toRatio(reported,delivered)],['Unsubscribe rate',toRatio(optOut,delivered)],['One event changes the rate by',delivered?showNumber(100/delivered)+' percentage points':'—']],{notes:['Use the same period and recipient scope for each count. A mailbox provider may use a different denominator.']});
111
+ }
112
+ export function listGrowth(v){
113
+ const start=integer(v,'starting_contacts'),add=integer(v,'new_per_month'),opt=numeric(v,'opt_out_pct',0,100)/100,invalid=numeric(v,'invalid_pct',0,100)/100,months=integer(v,'months',1,60);
114
+ check(opt+invalid<=1,'The total of the two monthly loss rates must be at most 100%.');
115
+ const rows=[];let list=start;
116
+ for(let i=1;i<=months;i++){
117
+ const lost=Math.round(list*(opt+invalid));const end=list-lost+add;
118
+ rows.push([i,list,add,lost,end]);list=end;
119
+ }
120
+ return tabular([['End of forecast',count(list)],['Net change',count(list-start)]],['Month','Starting contacts','Added','Lost','Ending contacts'],rows,'list-growth-forecast.csv',['The forecast applies both loss rates to the starting list each month, then adds new contacts. It uses constant assumptions for the forecast period.']);
121
+ }
122
+ function reportNumber(raw,label){
123
+ const str=String(raw??'').trim();
124
+ check(/^\d{1,10}$/.test(str)&&Number(str)<=1e9,`Enter whole counts for ${label}.`);return Number(str);
125
+ }
126
+ export function campaignReport(v){
127
+ const input=spreadsheet(v.csv);
128
+ const indices=['campaign','segment','sent','delivered','replies','meetings'].map(x=>column(input.columns,x));
129
+ const groups=new Map();
130
+ for(const r of input.rows){
131
+ const [name,segment,...value]=indices.map(i=>r[i]);
132
+ const nums=value.map((x,i)=>reportNumber(x,['sent','delivered','replies','meetings'][i]));
133
+ check(nums.every((n,i)=>i===0||n<=nums[i-1]),'Each row must follow sent ≥ delivered ≥ replies ≥ meetings. Check which counts you included.');
134
+ const id=JSON.stringify([name,segment]);const prev=groups.get(id)??[name,segment,0,0,0,0];
135
+ nums.forEach((n,i)=>{prev[i+2]+=n;});groups.set(id,prev);
136
+ }
137
+ const rows=[...groups.values()].sort((a,b)=>b[2]-a[2]).map(x=>[...x,toRatio(x[4],x[3]),toRatio(x[5],x[3])]);
138
+ return tabular([['Campaign/segment groups',count(rows.length)],['Total delivered',count(rows.reduce((sum,r)=>sum+r[3],0))]],['Campaign','Segment','Sent','Delivered','Replies','Meetings','Reply rate','Meeting rate'],rows,'campaign-comparison.csv',['Totals add the supplied rows. Use disjoint reporting periods or segments to avoid counting the same messages twice.']);
139
+ }
140
+ export async function campaignQr(v){
141
+ const url=safeHttp(v.url).href;
142
+ check(new TextEncoder().encode(url).length<=1600,'Use a campaign URL smaller than 1,600 bytes.');
143
+ const {createQR}=await import('./toolbox-vendor-qr.js');
144
+ let qr;
145
+ try{qr=createQR(url,{errorCorrectionLevel:'M'});}
146
+ catch{throw new InputError('This link is too long for a clear QR code at the selected correction level.');}
147
+ const n=qr.modules.size,cell=8;
148
+ const canvas=document.createElement('canvas');canvas.width=canvas.height=(n+8)*cell;
149
+ const ctx=canvas.getContext('2d');ctx.fillStyle='#fff';ctx.fillRect(0,0,canvas.width,canvas.height);ctx.fillStyle='#000';
150
+ for(let i=0;i<n;i++)for(let j=0;j<n;j++)if(qr.modules.get(i,j))ctx.fillRect((j+4)*cell,(i+4)*cell,cell,cell);
151
+ const png=await toBlob(canvas,'image/png');
152
+ return modelResult([['QR code','Ready'],['Image size',`${canvas.width} × ${canvas.height}`]],{image:canvas.toDataURL('image/png'),downloads:[{name:'campaign-qr.png',type:'image/png',text:png}],notes:['This static code contains the destination URL directly. Verify it with a scanner before adding it to printed materials.']});
153
+ }
@@ -0,0 +1,177 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS