Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1506 lines (1377 loc) · 68.5 KB
/
Copy pathscript.js
File metadata and controls
1506 lines (1377 loc) · 68.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const assessmentForm = document.querySelector("#assessmentForm");
const reportCard = document.querySelector("#reportCard");
const scanStatus = document.querySelector("#scanStatus");
let scanMotionTimer;
let latestReportData;
const LEAD_WEBHOOK_URL = "https://script.google.com/macros/s/AKfycbz2rN4obi9rRCvpauQoOPvRIzV_pE97SXebDdUOB-HmcG1Nw7bjFeWNVmotRCO4PoMY/exec";
const CALENDLY_URL = "https://calendly.com/vnsfirm/15min?back=1&month=2026-06";
const REPORT_CONTACT_EMAIL = "info@sb37score.com";
const LEAD_CONSENT_TEXT = "I consent to SB37 COA and its service providers storing and using my submitted information, website scan data, report details, and referral attribution to contact me by email, phone, and text about this assessment and related services.";
const AFFILIATE_STORAGE_KEY = "sb37AffiliateAttribution";
const AFFILIATE_MAX_AGE_DAYS = 90;
const AFFILIATE_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{1,39}$/;
const AFFILIATE_VANITY_PATHS = {
questionsb: "sb"
};
const categories = [
{
id: "disclosures",
name: "Required Disclosures",
weight: 20,
findings: [
{ id: "missingResponsibleAttorney", penalty: 10, label: "Missing responsible California attorney or firm name" },
{ id: "missingOfficeAddress", penalty: 5, label: "Missing office address or State Bar address signal" },
{ id: "missingAdDisclosure", penalty: 5, label: "Missing advertising, spokesperson, or dramatization disclosure" }
]
},
{
id: "claims",
name: "Case Results & Success Claims",
weight: 15,
findings: [
{ id: "settlementNoDisclaimer", penalty: 10, label: "Settlement, verdict, recovery, or result claims needing page-level context" },
{ id: "guaranteesOutcome", penalty: 15, label: "Guarantees, quick cash, immediate settlement, or outcome language" },
{ id: "misleadingStats", penalty: 15, label: "Misleading recovery statistics, volume claims, or inflated numbers" }
]
},
{
id: "awards",
name: "Awards & Specialization",
weight: 10,
findings: [
{ id: "unverifiedAwards", penalty: 5, label: "Unverified awards, badges, or rankings" },
{ id: "specialistClaims", penalty: 10, label: "Specialist, expert, or best-lawyer claims needing support" }
]
},
{
id: "ai",
name: "AI / Synthetic Content",
weight: 10,
findings: [
{ id: "aiAvatar", penalty: 10, label: "AI avatar, synthetic voice, or generated spokesperson" },
{ id: "aiAttorneyLikeness", penalty: 10, label: "AI attorney likeness, testimonial, or impersonation risk" },
{ id: "massAiContent", penalty: 10, label: "Mass AI content pages or unreviewed AI copy" }
]
},
{
id: "chatbot",
name: "Chatbot Risk",
weight: 10,
findings: [
{ id: "chatLegalAdvice", penalty: 10, label: "Chatbot gives legal advice or case-specific direction" },
{ id: "chatNoDisclaimer", penalty: 5, label: "Chatbot has no clear disclaimer or escalation rule" }
]
},
{
id: "intake",
name: "Intake & Call Center Risk",
weight: 10,
findings: [
{ id: "intakePromises", penalty: 10, label: "Intake or call center promises outcomes" },
{ id: "nonAttorneyGuidance", penalty: 10, label: "Non-attorney staff gives legal guidance" },
{ id: "noSupervisionProcess", penalty: 5, label: "No documented supervision or script review process" }
]
},
{
id: "vendor",
name: "Vendor-Created Content",
weight: 10,
findings: [
{ id: "unreviewedSeo", penalty: 5, label: "Unreviewed SEO, PPC, landing page, or lead-gen content" },
{ id: "noAttorneyOversight", penalty: 5, label: "No attorney approval rights before publication" },
{ id: "massAiContent", penalty: 10, label: "Mass AI content pages or unreviewed AI copy" }
]
},
{
id: "referral",
name: "Referral & Joint Advertising",
weight: 10,
findings: [
{ id: "coBrandedPages", penalty: 5, label: "Co-branded pages or joint advertising" },
{ id: "unclearReferral", penalty: 5, label: "Unclear referral relationship" },
{ id: "unclearReferral", penalty: 10, label: "Unclear lead-generator ownership" }
]
},
{
id: "transparency",
name: "Attorney Transparency",
weight: 5,
findings: [
{ id: "missingResponsibleAttorney", penalty: 5, label: "Attorney not clearly identified" }
]
}
];
const practiceRules = [
["Personal injury / mass tort", /\b(personal injury|car accident|truck accident|motorcycle|slip and fall|wrongful death|catastrophic|premises liability|mass tort|injury lawyer)\b/gi],
["Employment", /\b(employment|wrongful termination|workplace|wage and hour|harassment|discrimination|retaliation|labor law)\b/gi],
["Family law", /\b(divorce|custody|child support|spousal support|family law|prenup|domestic violence)\b/gi],
["Criminal defense", /\b(criminal defense|dui|dwi|felony|misdemeanor|arrest|expungement|domestic battery)\b/gi],
["Immigration", /\b(immigration|visa|green card|asylum|deportation|naturalization|citizenship|uscis)\b/gi],
["Estate planning", /\b(estate planning|trust|probate|will|living trust|power of attorney|trust administration)\b/gi],
["Bankruptcy", /\b(bankruptcy|chapter 7|chapter 13|debt relief|creditor harassment)\b/gi],
["Business / corporate", /\b(business law|corporate|contract|commercial litigation|partnership|merger|startup)\b/gi],
["Real estate", /\b(real estate|landlord|tenant|eviction|property dispute|construction defect)\b/gi]
];
const signalRules = [
{ id: "missingResponsibleAttorney", type: "missing", pattern: /\b(attorney advertising|responsible attorney|principal attorney|law offices of|law firm|lawyer|lawyers|legalservice|founder|founding partner|managing partner|esq\.|attorney at law|state bar-certified|certified criminal law specialist)\b/gi, evidence: "No obvious responsible attorney or firm identity phrase was detected in the extracted text." },
{ id: "missingOfficeAddress", type: "missing", pattern: /\b(\d{2,6}\s+[a-z0-9.' -]+\s+(street|st\.|avenue|ave\.|boulevard|blvd\.|road|rd\.|drive|dr\.|way|court|ct\.|place|pl\.|lane|ln\.|suite|ste\.|floor|fl\.)|streetaddress|addresslocality|addressregion|postalcode|postal address|state bar|calbar)\b/gi, evidence: "No obvious office address or State Bar address signal was detected in the extracted text." },
{ id: "missingAdDisclosure", type: "missing", pattern: /\b(advertisement|attorney advertising|actor portrayal|dramatization|spokesperson|paid spokesperson|results may vary|past results|no guarantee|not a guarantee|does not guarantee|not legal advice|does not create an attorney-client relationship|disclaimer)\b/gi, evidence: "No obvious advertising, dramatization, spokesperson, or results disclaimer language was detected." },
{ id: "settlementNoDisclaimer", pattern: /\b(\$[0-9][0-9,.]*\s*(million|m|k)?|settlement|verdict|recovered|recovery|won|results)\b/gi, evidence: "The site appears to discuss settlements, verdicts, recoveries, wins, or case results." },
{ id: "guaranteesOutcome", pattern: /\b(guarantee|guaranteed|no win no fee|win your case|maximum compensation|quick cash|cash now|immediate settlement|fast settlement|we will get you)\b/gi, evidence: "The site appears to use outcome, guarantee, quick-cash, or aggressive compensation language." },
{ id: "misleadingStats", pattern: /\b([0-9]+%\s*(success|win|settlement)|over\s+\$?[0-9][0-9,.]*|millions recovered|billions recovered|[0-9]+\+?\s*(cases|clients|settlements))\b/gi, evidence: "The site appears to use statistics, volume claims, or aggregate recovery numbers." },
{ id: "unverifiedAwards", pattern: /\b(award|awarded|super lawyers|best lawyers|top rated|avvo|martindale|million dollar advocates|rated|ranking|ranked)\b/gi, evidence: "The site appears to reference awards, badges, rankings, or third-party ratings." },
{ id: "specialistClaims", pattern: /\b(specialist|specialized|expert|experts|premier|leading|best|top|#1|number one)\b/gi, evidence: "The site appears to use specialist, expert, best, top, or similar superiority language." },
{ id: "aiAvatar", pattern: /\b(ai avatar|synthetic voice|virtual assistant|generated spokesperson|avatar|voice clone|deepfake)\b/gi, evidence: "The site appears to reference avatar, synthetic voice, virtual assistant, or generated spokesperson concepts." },
{ id: "aiAttorneyLikeness", pattern: /\b(ai attorney|virtual lawyer|robot lawyer|artificial intelligence lawyer|ai lawyer|automated legal advice)\b/gi, evidence: "The site appears to reference AI attorney, virtual lawyer, or automated legal advice concepts." },
{ id: "massAiContent", pattern: /\b(ai generated|generated by ai|artificial intelligence|chatgpt|machine learning|automated content|content automation)\b/gi, evidence: "The site appears to reference AI-generated content, artificial intelligence, or content automation." },
{ id: "chatLegalAdvice", pattern: /\b(ask our chatbot|chatbot|live chat|chat now|get legal advice now|answer your legal questions|free case evaluation)\b/gi, evidence: "The site appears to invite chat, chatbot, legal-question, or case-evaluation interactions." },
{ id: "chatNoDisclaimer", type: "missingWhenChat", pattern: /\b(not legal advice|does not create an attorney-client relationship|attorney-client relationship|consult an attorney)\b/gi, evidence: "Chat/intake language appeared, but no obvious no-legal-advice or no-attorney-client disclaimer was detected nearby in extracted text." },
{ id: "intakePromises", pattern: /\b(we can help you recover|you deserve compensation|we will fight|we get results|start your claim|get paid|settle your case)\b/gi, evidence: "The site appears to use intake-oriented outcome or compensation language." },
{ id: "nonAttorneyGuidance", pattern: /\b(intake specialist|case manager|legal assistant|call center|representative|advocate will call|specialist will review)\b/gi, evidence: "The site appears to reference non-attorney intake, case-management, or call-center roles." },
{ id: "noSupervisionProcess", type: "processReview", pattern: /\b(attorney reviewed|reviewed by an attorney|supervised by|attorney supervision|approved by)\b/gi, evidence: "Public pages cannot verify attorney supervision, intake scripts, or call-center review records." },
{ id: "unreviewedSeo", pattern: /\b(seo|landing page|lead generation|lead generator|ppc|google ads|sponsored|advertising partner)\b/gi, evidence: "The site appears to reference paid ads, SEO, landing pages, or lead-generation concepts." },
{ id: "noAttorneyOversight", type: "processReview", pattern: /\b(attorney reviewed|approved by attorney|attorney oversight|responsible attorney|supervised by)\b/gi, evidence: "Public pages cannot verify attorney approval rights for vendor-created marketing content." },
{ id: "coBrandedPages", pattern: /\b(co-counsel|affiliate|joint advertising|joint ad|sponsored by|in partnership with|powered by|partner network|advertising partner|marketing partner)\b/gi, evidence: "The site appears to reference partner, network, affiliate, co-counsel, or powered-by relationships." },
{ id: "unclearReferral", pattern: /\b(referral|lead generator|matching service|legal network|find a lawyer|connect you with|referred by|referred to us)\b/gi, evidence: "The site appears to reference referral, matching, lead-generator, or legal-network relationships." }
];
const findingTeasers = {
missingResponsibleAttorney: "Responsible attorney or firm identity was not obvious in the scanned text.",
missingOfficeAddress: "Office or State Bar address signals were not obvious in the scanned text.",
missingAdDisclosure: "Advertising, spokesperson, dramatization, or result-disclaimer language was not obvious.",
settlementNoDisclaimer: "Result, settlement, verdict, recovery, or win language appeared; disclaimer context is checked separately.",
guaranteesOutcome: "Outcome-style, guarantee, quick-cash, or aggressive compensation language appeared.",
misleadingStats: "Recovery numbers, volume claims, percentages, or aggregate statistics appeared.",
unverifiedAwards: "Award, badge, ranking, or third-party rating language appeared.",
specialistClaims: "Best, top, expert, specialist, or superiority language appeared.",
aiAvatar: "Synthetic voice, avatar, virtual assistant, or generated-spokesperson language appeared.",
aiAttorneyLikeness: "AI lawyer, virtual lawyer, or automated legal-advice language appeared.",
massAiContent: "AI-generated, artificial intelligence, or automated-content language appeared.",
chatLegalAdvice: "Chat, case-evaluation, or legal-question intake language appeared.",
chatNoDisclaimer: "Chat/intake signals appeared without an obvious no-legal-advice disclaimer nearby.",
intakePromises: "Intake copy appears to promise help recovering, settling, or getting paid.",
nonAttorneyGuidance: "Non-attorney intake, case manager, call center, or representative language appeared.",
noSupervisionProcess: "Public pages cannot verify attorney supervision, intake scripts, or call-center review records.",
unreviewedSeo: "SEO, PPC, landing-page, sponsored, or lead-generation language appeared.",
noAttorneyOversight: "Public pages cannot verify attorney approval rights for vendor-created marketing content.",
coBrandedPages: "Partner, network, affiliate, co-counsel, joint, or powered-by language appeared.",
unclearReferral: "Referral, referred, matching-service, legal-network, or lead-generator language appeared."
};
const MAX_SECOND_PASS_PAGES = 6;
const MAX_COMPLIANCE_PROBES = 8;
const MAX_LINKED_PAGES = 14;
const MAX_FILE_URLS = 3;
const CRAWL_BATCH_SIZE = 6;
const HOMEPAGE_TIMEOUT_MS = 6500;
const PAGE_TIMEOUT_MS = 4200;
const FILE_TIMEOUT_MS = 4200;
const scanPhases = [
"Normalizing domain and security headers",
"Discovering sitemap and priority internal pages",
"Probing disclaimer, terms, attorney, and results URLs",
"Reading homepage, header, footer, and schema",
"Checking attorney identity and office signals",
"Parsing disclaimers, terms, and advertising language",
"Reviewing case-result and recovery claim patterns",
"Screening awards, rankings, and specialization claims",
"Testing AI, chatbot, and intake-risk language",
"Mapping vendor, referral, and joint-advertising signals",
"Building SB37 category score"
];
function normalizeWebsite(rawUrl) {
const trimmed = rawUrl.trim();
if (!/^https?:\/\//i.test(trimmed)) {
return `https://${trimmed}`;
}
return trimmed;
}
function escapeHtml(value) {
return String(value)
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function isValidEmail(value) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
function phoneDigits(value) {
return String(value).replace(/\D/g, "");
}
function normalizeUsPhone(value) {
const digits = phoneDigits(value);
const national = digits.length === 11 && digits.startsWith("1") ? digits.slice(1) : digits;
if (national.length !== 10) return null;
return {
countryCode: "+1",
national,
e164: `+1${national}`
};
}
function normalizeAffiliateId(value) {
const normalized = String(value || "").trim().toLowerCase();
return AFFILIATE_ID_PATTERN.test(normalized) ? normalized : "";
}
function affiliateIdFromVanityPath(path) {
const normalizedPath = String(path || "").trim().toLowerCase();
return normalizeAffiliateId(AFFILIATE_VANITY_PATHS[normalizedPath] || normalizedPath);
}
function affiliateParamFromUrl() {
const params = new URLSearchParams(window.location.search);
const candidates = ["ref", "affiliate", "aff", "partner", "utm_source"];
for (const key of candidates) {
const affiliateId = normalizeAffiliateId(params.get(key));
if (affiliateId) {
return { affiliateId, sourceParam: key };
}
}
return null;
}
function affiliateParamFromPath() {
const path = window.location.pathname.replace(/^\/+|\/+$/g, "");
if (!path || path.indexOf("/") !== -1) return null;
if (/^(index\.html|about\.html|terms\.html|example\.html|404\.html|assets|SB37)$/i.test(path)) return null;
const affiliateId = affiliateIdFromVanityPath(path);
return affiliateId ? { affiliateId, sourceParam: "path" } : null;
}
function readStoredAffiliateAttribution() {
try {
const raw = window.localStorage.getItem(AFFILIATE_STORAGE_KEY);
if (!raw) return null;
const attribution = JSON.parse(raw);
const affiliateId = normalizeAffiliateId(attribution.affiliateId);
if (!affiliateId || !attribution.firstSeenAt) return null;
const ageMs = Date.now() - new Date(attribution.firstSeenAt).getTime();
if (!Number.isFinite(ageMs) || ageMs < 0 || ageMs > AFFILIATE_MAX_AGE_DAYS * 24 * 60 * 60 * 1000) {
window.localStorage.removeItem(AFFILIATE_STORAGE_KEY);
return null;
}
return { ...attribution, affiliateId };
} catch (error) {
window.localStorage.removeItem(AFFILIATE_STORAGE_KEY);
return null;
}
}
function captureAffiliateAttribution() {
const current = affiliateParamFromUrl() || affiliateParamFromPath();
const stored = readStoredAffiliateAttribution();
if (!current) return stored;
const now = new Date().toISOString();
const attribution = {
affiliateId: current.affiliateId,
sourceParam: current.sourceParam,
landingPage: window.location.href.slice(0, 500),
firstSeenAt: stored && stored.affiliateId === current.affiliateId ? stored.firstSeenAt : now,
lastSeenAt: now,
clickId: stored && stored.affiliateId === current.affiliateId && stored.clickId
? stored.clickId
: `sb37-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
};
window.localStorage.setItem(AFFILIATE_STORAGE_KEY, JSON.stringify(attribution));
return attribution;
}
function affiliatePayloadFields() {
const attribution = readStoredAffiliateAttribution();
if (!attribution) return {};
return {
affiliateId: attribution.affiliateId,
affiliateSourceParam: attribution.sourceParam || "",
affiliateLandingPage: attribution.landingPage || "",
affiliateFirstSeenAt: attribution.firstSeenAt || "",
affiliateLastSeenAt: attribution.lastSeenAt || "",
affiliateClickId: attribution.clickId || "",
affiliateAttributionWindowDays: AFFILIATE_MAX_AGE_DAYS,
affiliatePayoutStatus: "pending_review",
affiliatePayoutNotes: ""
};
}
function countMatches(text, pattern) {
return Array.from(text.matchAll(pattern)).length;
}
function topMatches(text, pattern, limit = 3) {
return Array.from(new Set(Array.from(text.matchAll(pattern)).map((match) => match[0].trim())))
.filter(Boolean)
.slice(0, limit);
}
function htmlToText(raw) {
return raw.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi, (match, attrs, content) => (
/application\/ld\+json/i.test(attrs) ? ` ${content} ` : " "
))
.replace(/<style[\s\S]*?<\/style>/gi, " ")
.replace(/<[^>]+>/g, " ")
.replace(/\s+/g, " ")
.trim();
}
function extractTaggedHtmlText(raw, tags) {
if (!raw) return "";
return tags.flatMap((tag) => (
Array.from(raw.matchAll(new RegExp(`<${tag}\\b[^>]*>[\\s\\S]*?<\\/${tag}>`, "gi")))
.map((match) => htmlToText(match[0]))
)).join(" ");
}
function extractDisclosureContext(raw) {
const pageRegions = extractTaggedHtmlText(raw, ["header", "nav", "aside", "main", "footer"]);
const metaText = Array.from(raw.matchAll(/<meta\b[^>]*(?:name|property)=["']?(?:description|og:description|twitter:description)["']?[^>]*content=["']([^"']+)["'][^>]*>/gi))
.map((match) => match[1])
.join(" ");
const imageText = Array.from(raw.matchAll(/\b(?:alt|aria-label|title)=["']([^"']+)["']/gi))
.map((match) => match[1])
.join(" ");
return `${pageRegions} ${metaText} ${imageText}`.replace(/\s+/g, " ").trim();
}
function urlPriorityScore(url) {
let score = 0;
const lowerUrl = url.toLowerCase();
if (/\b(disclaimer|terms|privacy|attorney-advertising|advertising-disclaimer|legal-notice)\b/i.test(lowerUrl)) score -= 80;
if (/\b(about|about-us|attorneys|our-attorneys|team|firm|contact|profile|bio|state-bar|statebar|calbar)\b/i.test(lowerUrl)) score -= 60;
if (/\b(results|case-results|verdicts|settlements|testimonials|reviews|awards|media|press)\b/i.test(lowerUrl)) score -= 40;
if (/\b(chat|intake|consultation|free-case-evaluation|referral|partners|co-counsel)\b/i.test(lowerUrl)) score -= 25;
if (/\b(blog|news|article|category|tag|author|page\/[0-9]+)\b/i.test(lowerUrl)) score += 25;
if (/\b(lawyer|attorney)\b/i.test(lowerUrl) && !/\b(attorneys|our-attorneys|attorney-advertising)\b/i.test(lowerUrl)) score += 12;
return score;
}
function isProbablyHtmlPage(url) {
return !/\.(pdf|docx?|rtf|txt|csv|xlsx?|pptx?|zip|jpg|jpeg|png|gif|svg|webp|mp4|mov|mp3|css|js|woff2?|ttf|ico)(\?|$)/i.test(url);
}
function isTextFileUrl(url) {
return /\.(pdf|docx?|rtf|txt)(\?|$)/i.test(url);
}
function normalizeInternalUrl(href, baseUrl) {
try {
const base = new URL(baseUrl);
const linked = new URL(href, base);
if (linked.hostname.replace(/^www\./, "") !== base.hostname.replace(/^www\./, "")) return "";
linked.hash = "";
linked.search = "";
return linked.href;
} catch (error) {
return "";
}
}
function extractLinkedUrls(raw, baseUrl) {
const hrefLinks = Array.from(raw.matchAll(/\bhref\s*=\s*["']?([^"'\s>]+)/gi)).map((match) => match[1]);
const markdownLinks = Array.from(raw.matchAll(/\]\(([^)]+)\)/g)).map((match) => match[1]);
const jsonLinks = Array.from(raw.matchAll(/"url"\s*:\s*"([^"]+)"/gi)).map((match) => match[1].replaceAll("\\/", "/"));
const links = hrefLinks.concat(markdownLinks, jsonLinks)
.filter((href) => href && !href.startsWith("#") && !href.startsWith("mailto:") && !href.startsWith("tel:"));
return Array.from(new Set(links.map((href) => normalizeInternalUrl(href, baseUrl)).filter(Boolean)));
}
function prioritizeUrls(urls) {
return Array.from(new Set(urls)).sort((a, b) => {
const priorityDelta = urlPriorityScore(a) - urlPriorityScore(b);
if (priorityDelta !== 0) return priorityDelta;
return a.length - b.length;
});
}
function commonComplianceUrls(baseUrl, linkedUrls = []) {
const base = new URL(baseUrl);
const sameSiteLink = linkedUrls.find((url) => {
try {
const linked = new URL(url);
return linked.hostname.replace(/^www\./, "") === base.hostname.replace(/^www\./, "");
} catch (error) {
return false;
}
});
const origin = sameSiteLink ? new URL(sameSiteLink).origin : base.origin;
return [
"/disclaimer/",
"/disclaimer",
"/legal-disclaimer/",
"/attorney-advertising/",
"/terms/",
"/terms-of-use/",
"/privacy-policy/",
"/privacy/",
"/about/",
"/about-us/",
"/attorneys/",
"/our-attorneys/",
"/team/",
"/contact/",
"/results/",
"/case-results/",
"/testimonials/"
].map((path) => `${origin}${path}`);
}
function isLikelyUsefulPage(page) {
if (!page || !page.text || page.text.length < 80) return false;
return !/\b(404|page not found|not found|nothing found|this page could not be found)\b/i.test(page.text.slice(0, 700));
}
async function fetchRawUrl(url, timeoutMs = PAGE_TIMEOUT_MS) {
const direct = await fetchWithTimeout(url, timeoutMs);
if (direct) return direct;
return fetchWithTimeout(`https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`, timeoutMs);
}
function sitemapCandidates(baseUrl) {
const origin = new URL(baseUrl).origin;
return [
`${origin}/sitemap.xml`,
`${origin}/sitemap_index.xml`,
`${origin}/sitemap-index.xml`
];
}
function parseSitemapUrls(raw, baseUrl) {
const locUrls = Array.from(raw.matchAll(/<loc>\s*([^<]+)\s*<\/loc>/gi)).map((match) => match[1].trim());
const textUrls = Array.from(raw.matchAll(/https?:\/\/[^\s"'<>]+/gi)).map((match) => match[0].trim());
return locUrls.concat(textUrls).map((href) => normalizeInternalUrl(href, baseUrl)).filter(Boolean);
}
async function discoverSitemapUrls(baseUrl) {
const firstPass = await Promise.allSettled(sitemapCandidates(baseUrl).map(async (url) => ({
url,
raw: await fetchRawUrl(url, 2500)
})));
const found = firstPass
.filter((result) => result.status === "fulfilled" && result.value.raw)
.flatMap((result) => parseSitemapUrls(result.value.raw, baseUrl));
const nestedSitemaps = found.filter((url) => /sitemap/i.test(url)).slice(0, 4);
const nested = await Promise.allSettled(nestedSitemaps.map(async (url) => parseSitemapUrls(await fetchRawUrl(url, 2500), baseUrl)));
return Array.from(new Set(found.concat(nested.flatMap((result) => result.status === "fulfilled" ? result.value : []))));
}
async function runInBatches(items, batchSize, worker) {
const results = [];
for (let index = 0; index < items.length; index += batchSize) {
const batch = items.slice(index, index + batchSize);
const settled = await Promise.allSettled(batch.map(worker));
results.push(...settled);
}
return results;
}
async function fetchWithTimeout(url, timeoutMs = 12000) {
const controller = new AbortController();
const timeout = window.setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, { cache: "no-store", signal: controller.signal });
if (!response.ok) return "";
return await response.text();
} finally {
window.clearTimeout(timeout);
}
}
async function extractOnePage(url, timeoutMs = 12000) {
const allOriginsUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`;
const parsedUrl = new URL(url);
const readerUrl = `https://r.jina.ai/http://${parsedUrl.host}${parsedUrl.pathname}`;
const alternateReaderUrl = `https://r.jina.ai/http://${parsedUrl.host}${parsedUrl.pathname}${parsedUrl.search}`;
const [directHtml, html, readable, alternateReadable] = await Promise.allSettled([
fetchWithTimeout(url, timeoutMs),
fetchWithTimeout(allOriginsUrl, timeoutMs),
fetchWithTimeout(readerUrl, timeoutMs),
fetchWithTimeout(alternateReaderUrl, timeoutMs)
]);
const rawHtml = directHtml.status === "fulfilled" && directHtml.value
? directHtml.value
: html.status === "fulfilled" ? html.value : "";
const crawlerVisibleText = extractDisclosureContext(rawHtml);
const readerText = readable.status === "fulfilled" ? readable.value : "";
const alternateReaderText = alternateReadable.status === "fulfilled" ? alternateReadable.value : "";
const htmlText = `${crawlerVisibleText} ${htmlToText(rawHtml)}`.replace(/\s+/g, " ").trim();
const fallbackText = `${readerText} ${alternateReaderText}`.replace(/\s+/g, " ").trim();
const text = htmlText || fallbackText;
return { rawHtml, text };
}
async function readWebsiteText(url) {
let normalized = normalizeWebsite(url);
let homepage = await extractOnePage(normalized, HOMEPAGE_TIMEOUT_MS);
if ((!homepage.text || homepage.text.length < 80) && !new URL(normalized).hostname.startsWith("www.")) {
const retryUrl = new URL(normalized);
retryUrl.hostname = `www.${retryUrl.hostname}`;
const retryHomepage = await extractOnePage(retryUrl.href, HOMEPAGE_TIMEOUT_MS);
if (retryHomepage.text && retryHomepage.text.length >= 80) {
normalized = retryUrl.href;
homepage = retryHomepage;
}
}
if (!homepage.text || homepage.text.length < 80) {
throw new Error("Website extraction failed");
}
if (scanStatus) setScanStatus("scanning", "Discovering sitemap, internal pages, headers, footers, legal pages, attorney pages, and text/PDF-style files.");
const sitemapUrls = await discoverSitemapUrls(normalized);
const homepageLinks = extractLinkedUrls(`${homepage.rawHtml} ${homepage.text}`, normalized);
const linkedCandidates = prioritizeUrls(sitemapUrls.concat(homepageLinks));
const complianceProbeUrls = prioritizeUrls(commonComplianceUrls(normalized, linkedCandidates)).slice(0, MAX_COMPLIANCE_PROBES);
const linkedPageUrls = linkedCandidates
.filter((linkedUrl) => linkedUrl !== normalized && isProbablyHtmlPage(linkedUrl))
.slice(0, MAX_LINKED_PAGES);
const firstPassCandidates = prioritizeUrls(complianceProbeUrls.concat(linkedPageUrls));
const fileUrls = linkedCandidates.concat(complianceProbeUrls).filter(isTextFileUrl).slice(0, MAX_FILE_URLS);
const pageUrls = firstPassCandidates
.filter((linkedUrl) => linkedUrl !== normalized && isProbablyHtmlPage(linkedUrl))
.slice(0, MAX_COMPLIANCE_PROBES + MAX_LINKED_PAGES);
if (scanStatus) setScanStatus("scanning", `Building preview from ${pageUrls.length + 1} priority pages and ${fileUrls.length} file URLs.`);
const pageResults = await runInBatches(pageUrls, CRAWL_BATCH_SIZE, (link) => extractOnePage(link, PAGE_TIMEOUT_MS));
const successfulPages = pageResults
.filter((result) => result.status === "fulfilled")
.map((result) => result.value)
.filter(isLikelyUsefulPage);
const secondPassLinks = prioritizeUrls(successfulPages.flatMap((page) => extractLinkedUrls(`${page.rawHtml} ${page.text}`, normalized)))
.filter((linkedUrl) => linkedUrl !== normalized && !pageUrls.includes(linkedUrl) && isProbablyHtmlPage(linkedUrl))
.slice(0, MAX_SECOND_PASS_PAGES);
const secondPassResults = await runInBatches(secondPassLinks, CRAWL_BATCH_SIZE, (link) => extractOnePage(link, PAGE_TIMEOUT_MS));
const successfulSecondPassPages = secondPassResults
.filter((result) => result.status === "fulfilled")
.map((result) => result.value)
.filter(isLikelyUsefulPage);
const fileResults = await runInBatches(fileUrls, CRAWL_BATCH_SIZE, (link) => fetchWithTimeout(`https://r.jina.ai/http://${link}`, FILE_TIMEOUT_MS));
const successfulFiles = fileResults
.filter((result) => result.status === "fulfilled" && result.value)
.map((result) => result.value);
const combinedText = [homepage.text]
.concat(successfulPages.map((page) => page.text), successfulSecondPassPages.map((page) => page.text), successfulFiles)
.join(" ")
.replace(/\s+/g, " ")
.trim();
const pagesScanned = 1 + successfulPages.length + successfulSecondPassPages.length;
const filesScanned = successfulFiles.length;
const urlsChecked = 1 + pageUrls.length + secondPassLinks.length + fileUrls.length;
return {
normalizedUrl: normalized,
sourceText: combinedText.slice(0, 450000),
pagesScanned,
filesScanned,
urlsChecked,
extractionStatus: `Preview scan checked ${urlsChecked} URLs and analyzed ${pagesScanned} readable pages${filesScanned ? ` plus ${filesScanned} file URLs` : ""}`
};
}
function inferPractice(text, url) {
const scanText = `${text} ${url}`;
const scored = practiceRules
.map(([name, pattern]) => ({ name, count: countMatches(scanText, pattern) }))
.sort((a, b) => b.count - a.count);
const winner = scored[0];
return winner && winner.count > 0 ? winner.name : "General / mixed legal services";
}
function detectSignals(text, url) {
const scanText = `${text} ${url}`;
const hasChat = /\b(chatbot|live chat|chat now|free case evaluation|case evaluation|contact us|call now)\b/i.test(scanText);
const signals = new Set();
const evidence = [];
signalRules.forEach((rule) => {
const matches = topMatches(scanText, rule.pattern);
const hasMatch = matches.length > 0;
const shouldTrigger =
(rule.type === "missing" && !hasMatch) ||
(rule.type === "missingWhenChat" && hasChat && !hasMatch) ||
(rule.type === "processReview") ||
(!rule.type && hasMatch);
if (shouldTrigger) {
signals.add(rule.id);
evidence.push({
id: rule.id,
label: rule.evidence,
matches
});
} else if (rule.type === "missing" && hasMatch) {
evidence.push({
id: `${rule.id}Found`,
label: `Disclosure signal found: ${rule.evidence.replace(/^No obvious /, "").replace(/ was detected.*$/, "")}.`,
matches
});
}
});
return { signals, evidence };
}
function scoreCategory(category, signals) {
const activeFindings = category.findings.filter((finding) => signals.has(finding.id));
const rawPenalty = activeFindings.reduce((sum, finding) => {
const hasDisclosureContext = !signals.has("missingAdDisclosure");
const adjustedPenalty = finding.id === "settlementNoDisclaimer" && hasDisclosureContext
? Math.min(finding.penalty, 4)
: finding.penalty;
return sum + adjustedPenalty;
}, 0);
const cappedPenalty = Math.min(category.weight, rawPenalty);
const percent = Math.max(0, Math.round(((category.weight - cappedPenalty) / category.weight) * 100));
return { ...category, activeFindings, rawPenalty, cappedPenalty, percent };
}
function scoreAssessment({ signals, url, sourceText, evidence, extractionStatus, pagesScanned = 1, filesScanned = 0, urlsChecked = pagesScanned }) {
const categoryScores = categories.map((category) => scoreCategory(category, signals));
let totalPenalty = categoryScores.reduce((sum, category) => sum + category.cappedPenalty, 0);
const inferredFindings = [];
if (/\b(settlement|cash|win|verdict|injury|accident)\b/i.test(url)) {
totalPenalty += 5;
inferredFindings.push("URL language suggests outcome, settlement, injury, accident, cash, or win positioning. Review page copy for guarantees and context.");
}
const score = Math.max(0, Math.min(100, 100 - totalPenalty));
const level = score >= 90 ? "low" : score >= 75 ? "medium" : score >= 60 ? "elevated" : score >= 40 ? "high" : "critical";
const activeFindings = categoryScores.flatMap((category) =>
category.activeFindings.map((finding) => `${category.name}: ${finding.label}`)
);
const deltas = activeFindings.concat(inferredFindings);
if (!deltas.length) {
deltas.push("No high-risk homepage signals were detected. Confirm required disclosures, attorney identity, review records, and monitoring cadence before relying on the score.");
}
const nextSteps = [
"Use a focused COA review to check public pages, landing pages, paid ads, referral funnels, intake scripts, chatbots, and vendor-controlled assets.",
"Verify attorney identity, office address, advertising disclosures, spokesperson disclosures, and case-result disclaimers on each high-traffic page.",
"Collect substantiation files for awards, rankings, success claims, settlement numbers, and recovery statistics.",
"Document vendor approval rights, update workflows, chatbot scripts, transcript sampling, and a practical monitoring cadence."
];
return {
score,
level,
categoryScores,
deltas,
nextSteps,
evidence,
extractionStatus,
pagesScanned,
filesScanned,
urlsChecked,
wordsScanned: sourceText.split(/\s+/).filter(Boolean).length,
signalsChecked: signalRules.length,
triggeredCount: signals.size + inferredFindings.length
};
}
function levelLabel(level) {
return {
low: "Looks Stable",
medium: "Review Suggested",
elevated: "Review Suggested",
high: "Priority Review",
critical: "Priority Review"
}[level];
}
function rowClass(percent) {
if (percent >= 85) return "clear";
if (percent >= 60) return "watch";
return "alert";
}
function isPriorityReviewCategory(category) {
return category.activeFindings.length > 0 && category.percent < 60;
}
function scoreTone(level) {
if (level === "low") return "clear";
if (level === "medium" || level === "elevated") return "watch";
return "alert";
}
function scoreColor(score) {
if (score >= 90) return "#27a76f";
if (score >= 60) return "#c56a16";
return "#b43b45";
}
function reviewLabel(percent) {
if (percent >= 85) return "Looks stable";
if (percent >= 60) return "Review suggested";
return "Priority review";
}
function renderScanProgress(website) {
reportCard.innerHTML = `
<div class="scan-progress" aria-live="polite">
<div class="scan-orbit" aria-hidden="true">
<span></span>
<span></span>
<span></span>
</div>
<div class="scan-copy">
<span class="report-badge">Scanning</span>
<h3>Building SB37 report</h3>
<p>${escapeHtml(website)}</p>
</div>
<div class="scan-bar" aria-hidden="true"><span></span></div>
<div class="scan-phase">
<strong id="scanPhaseLabel">${escapeHtml(scanPhases[0])}</strong>
<span id="scanPercent">8%</span>
</div>
<div class="scan-modules" aria-label="Analysis modules">
${categories.map((category, index) => `
<span class="${index === 0 ? "active" : ""}">${escapeHtml(category.name)}</span>
`).join("")}
</div>
</div>
`;
}
function startScanMotion() {
window.clearInterval(scanMotionTimer);
let step = 0;
scanMotionTimer = window.setInterval(() => {
step += 1;
const phaseLabel = document.querySelector("#scanPhaseLabel");
const percentLabel = document.querySelector("#scanPercent");
const moduleChips = Array.from(document.querySelectorAll(".scan-modules span"));
if (!phaseLabel || !percentLabel || !moduleChips.length) return;
const phase = scanPhases[step % scanPhases.length];
const percent = Math.min(94, 8 + step * 6);
phaseLabel.textContent = phase;
percentLabel.textContent = `${percent}%`;
moduleChips.forEach((chip, index) => {
chip.classList.toggle("active", index === step % moduleChips.length);
chip.classList.toggle("done", index < step % (moduleChips.length + 1));
});
}, 1450);
}
function stopScanMotion() {
window.clearInterval(scanMotionTimer);
scanMotionTimer = null;
}
function categoryPreviewReason(category) {
if (!category.activeFindings.length) {
return "No obvious preview signal triggered in this area.";
}
const teasers = category.activeFindings
.map((finding) => findingTeasers[finding.id] || finding.label)
.filter(Boolean);
const uniqueTeasers = Array.from(new Set(teasers)).slice(0, 2);
const suffix = category.activeFindings.length > uniqueTeasers.length ? " Additional signals may need review." : " Review this area in context.";
return `${uniqueTeasers.join(" ")}${suffix}`;
}
function renderMarketBoard(categoryScores, limit = categoryScores.length, options = {}) {
const { reviewOnly = false } = options;
const filtered = reviewOnly
? categoryScores.filter(isPriorityReviewCategory)
: categoryScores;
const ordered = [...filtered].sort((a, b) => a.percent - b.percent).slice(0, limit);
if (!ordered.length) {
return `
<div class="review-row clear">
<div>
<strong>No active review areas</strong>
<span>Looks stable</span>
<p>No red priority review signal triggered in the top review areas.</p>
</div>
</div>
`;
}
return ordered.map((category) => `
<div class="review-row ${rowClass(category.percent)}">
<div>
<strong>${escapeHtml(category.name)}</strong>
<span>${reviewLabel(category.percent)}</span>
<p>${escapeHtml(categoryPreviewReason(category))}</p>
</div>
</div>
`).join("");
}
function renderCompactStats(scoreData) {
return `
<div class="report-statline" aria-label="Scan summary">
<span>${scoreData.urlsChecked} URLs</span>
<span>${scoreData.pagesScanned} pages</span>
<span>${scoreData.signalsChecked} signals</span>
</div>
`;
}
const categoryFixes = {
disclosures: {
risk: "Disclosure signals are a useful first place to improve clarity. If disclaimer language is only in a footer or legal page, the next step is to make the right context easier to see near important claims and forms.",
firstFix: "Place attorney advertising, responsible attorney, firm identity, office address, and disclaimer language in visible page-level locations.",
implementation: [
"Create a reusable disclosure block for every landing page template.",
"Place the block near high-intent CTAs, chat widgets, case-result sections, testimonial sections, and footer.",
"Confirm the responsible attorney or firm identity appears in crawlable text, not only inside an image.",
"Snapshot before and after versions for the compliance file."
],
evidence: [
"Screenshots of each page template after update.",
"Responsible attorney approval note.",
"Version date and URL inventory."
],
serviceNeed: "A guided review can help confirm which page templates need small edits and which claims need closer context."
},
claims: {
risk: "Result and compensation language deserves careful review because consumers may read it as an expectation about their own matter unless the page gives enough context.",
firstFix: "Pair every result, recovery, settlement, verdict, and compensation claim with nearby context and past-results disclaimer language.",
implementation: [
"Inventory every dollar amount, verdict, settlement, recovered, won, success, and compensation phrase.",
"Add matter-specific context where allowed: jurisdiction, case type, date range, and that every case is different.",
"Move past-results disclaimer language close to the claim, not only in the footer.",
"Remove guarantee, quick-cash, fast-settlement, and maximum-compensation phrasing unless counsel approves exact wording."
],
evidence: [
"Result-claim spreadsheet with URL, claim text, source, approval date, and disclaimer placement.",
"Backup documents for each published number or outcome.",
"Attorney signoff for edited copy."
],
serviceNeed: "A guided review can separate routine success language from claims that should be rewritten or supported with better context."
},
awards: {
risk: "Award, ranking, top, best, expert, and specialist language is easier to trust when the source, date, and limits are visible.",
firstFix: "Add source, date, ranking body, eligibility criteria, and limitations near award, best, top, or specialist claims.",
implementation: [
"Build an awards and rankings substantiation file.",
"Add source/date language beside each badge or superiority claim.",
"Separate certified-specialist claims from informal expert/top/best marketing language.",
"Remove unsupported best/top/#1 wording or replace it with sourced, factual language."
],
evidence: [
"Award certificates or source pages.",
"Selection methodology where available.",
"Attorney approval for each claim."
],
serviceNeed: "A guided review can help organize which badges are already supported and which need source language added."
},
ai: {
risk: "AI-assisted content is easier to manage when the firm can show who reviewed it before publication.",
firstFix: "Document attorney review for AI-assisted content and avoid any copy that implies automated legal advice or synthetic attorney endorsement.",
implementation: [
"Label AI-assisted workflows internally, even if not public-facing.",
"Require attorney review before AI-assisted content, images, video, or chat copy goes live.",
"Avoid AI lawyer, virtual lawyer, automated legal advice, synthetic voice, or avatar claims.",
"Keep prompts, drafts, approvals, and final copy in a review log."
],
evidence: [
"AI content review log.",
"Approval workflow screenshots.",
"Vendor AI-use disclosure and takedown terms."
],
serviceNeed: "A guided workflow can help create a simple approval log before AI-assisted content spreads across pages and vendors."
},
chatbot: {
risk: "Chat and case-evaluation flows are more customer-friendly when users understand what the tool can and cannot do before they submit details.",
firstFix: "Add no-legal-advice and no-attorney-client language before chat or case-evaluation flows, with clear attorney escalation rules.",
implementation: [
"Add pre-chat disclaimer language before the user submits facts.",
"Block the bot from giving case-specific legal conclusions.",
"Create escalation rules for urgent, jurisdictional, conflict, and representation questions.",
"Sample transcripts monthly and document follow-up changes."
],
evidence: [
"Chat script and prompt policy.",
"Transcript QA samples.",
"Escalation and conflict-screen procedure."
],
serviceNeed: "A guided review can test the flow itself, not just the page where the chat or form appears."
},
intake: {
risk: "Intake copy and call-center scripts are where website interest becomes a real conversation, so clear scripts help protect both the consumer and the firm.",
firstFix: "Review intake scripts for outcome promises and document attorney supervision for non-attorney staff or call center workflows.",
implementation: [
"Collect scripts, form autoresponders, SMS templates, call prompts, and CRM nurture copy.",
"Remove promises about settlement speed, payment, case value, or guaranteed help.",
"Add supervision and escalation rules for non-attorney staff.",
"Train intake staff and record the training date."
],
evidence: [
"Approved script library.",
"Training records.",
"Call QA checklist and sample review log."
],
serviceNeed: "A guided review can help locate the forms, scripts, autoresponders, and CRM messages that are easy to miss from a website-only scan."
},
vendor: {
risk: "Vendor-created SEO, PPC, landing pages, and lead funnels often change quickly, so the next step is making review and approval easier to prove.",
firstFix: "Require attorney approval before vendor-created SEO, PPC, landing pages, content updates, or lead-generation copy goes live.",
implementation: [
"List every vendor with publishing access or campaign control.",
"Add attorney approval rights and takedown timing to vendor workflows.",
"Review paid landing pages, ad copy, dynamic inserts, and SEO pages against the same rules as the main site.",
"Create a monthly change-detection process."
],
evidence: [
"Vendor roster and access list.",
"Approval workflow records.",
"Ad and landing-page archive."
],
serviceNeed: "A guided review can help connect the main website, ad accounts, landing pages, and vendor workflows into one approval trail."
},
referral: {
risk: "Referral, matching, network, affiliate, partner, and co-counsel language is more useful when consumers can tell who owns the advertising and who will contact them.",
firstFix: "Clarify referral, co-counsel, partner, network, affiliate, and lead-generator relationships wherever those signals appear.",
implementation: [
"Inventory every page and funnel that mentions referrals, partners, networks, co-counsel, or powered-by language.",
"Clarify who owns the advertising and who will contact the consumer.",
"Add required relationship disclosures near lead forms and comparison pages.",
"Confirm lead-generator contracts match the public-facing language."
],
evidence: [
"Referral and lead-source inventory.",
"Co-counsel or lead-gen agreements.",
"Screenshots of relationship disclosures."
],
serviceNeed: "A guided review can compare the public wording against the firm’s actual referral, co-counsel, or lead-source process."
},
transparency: {
risk: "Attorney and firm identity details help visitors understand who is responsible for the advertisement and how to verify the firm.",
firstFix: "Make attorney identity, firm ownership, office location, and responsible-contact details easy to find from the scanned pages.",
implementation: [
"Make attorney and firm identity visible in crawlable text.",
"Add office/contact details to footer, contact page, attorney page, and landing-page templates.",
"Link attorney bios from practice pages and high-conversion pages.",
"Archive screenshots after deployment."
],
evidence: [
"Attorney bio inventory.",
"Office-address screenshots.",
"Responsible-contact approval record."
],
serviceNeed: "A guided review can make sure those details stay consistent across the main site and any standalone landing pages."
}
};
function categoryFix(category) {
return categoryFixes[category.id] || {
risk: "This area is worth a closer look because the preview found public-facing signals that may benefit from clearer context, documentation, or supervision.",
firstFix: "Review this category and document a simple next-step plan.",
implementation: [
"Inventory affected pages and assets.",
"Confirm the correct disclaimer, substantiation, and approval record.",
"Update the public copy and archive the before/after version."
],
evidence: [
"URL inventory.",
"Attorney approval record.",
"Before/after screenshots."
],
serviceNeed: "A guided review can separate true issues from noisy public-page signals."
};
}
function renderProduceReportForm() {
return `
<section class="produce-report-card">
<div class="produce-copy">
<span class="report-badge">Free first step</span>