Repository navigation
Expand file tree
/
Copy pathBlogPulse.js
More file actions
4121 lines (4009 loc) · 291 KB
/
Copy pathBlogPulse.js
File metadata and controls
4121 lines (4009 loc) · 291 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
// Variables used by Scriptable.
// These must be at the very top of the file. Do not edit.
// icon-color: deep-blue; icon-glyph: rss;
/*
* BlogPulse — a Feedly-style reader for tech company blogs, for Scriptable on iPhone.
* https://github.com/gadominas/BlogPulse
*
* - Checks every followed blog each time the app opens and highlights what's new
* - Add blogs by searching (built-in list + Feedly's public feed search) or by pasting any address
* - Mark read, rate 1–3 stars (ratings train Picks), group by day or week, topic pages
* - Optional Claude or OpenAI: summaries, categories, the Story, TL;DRs and invites to read
* - Home Screen widget in the shared frame (app-blueprints · widgets), in-app updates from GitHub
*
* - Opens on a 2.4 s launch screen with the BlogPulse logo (app-blueprints · launch-screen)
* - Without an AI key, an occasional card shows what AI adds and leads to AI settings (app-blueprints · ai-invitation)
* - The BLUEPRINTS block below lists every shared blueprint this app follows (Settings › Built with)
*
* Data lives in iCloud Drive › Scriptable › BlogPulse (JSON files). Keys live in the iOS Keychain.
*/
// This build's version. When releasing, bump it and add a matching entry to releases.json.
const VERSION = '1.23.0';
const APP_ID = 'blogpulse'; // unique per app, never changes
const REPO_RAW = 'https://raw.githubusercontent.com/gadominas/BlogPulse/main/';
const SCRIPT_FILE = 'BlogPulse.js'; // the script's file name in the repository
const UPDATE_SNOOZE_MS = 2 * 24 * 3600 * 1000; // "Later" = 2 days
const KC_UPDATE_SNOOZE = 'blogpulse-update-snooze'; // Keychain key, unique per app
// In a native shell (BuildIt) new versions come from the App Store or TestFlight, never from GitHub (Step 8).
const NATIVE_SHELL = (() => { try { return config.runsInNativeShell === true; } catch (e) { return false; } })();
// ── Anonymous usage counts (opt-in), sent to PostHog (app-blueprints · usage-analytics) ──
// Nothing is sent until KEY is filled in AND the person agrees. Each event carries a random install ID
// (made on this iPhone, not linked to any account), the app version and counts: never names, IDs from
// other services, text, photos or anything the app read. Events are anonymous (no person profiles).
// The key is PostHog's project key, made to sit in public apps: it can only add events.
// HOST must be the region the project lives in: PostHog's other region answers "accepted" and then drops the events.
const USAGE = { HOST: 'https://us.i.posthog.com', KEY: 'phc_yAi2PxJCRioWEKLF3uockdCf3QvyQdNABivwqpE4NCWR' }; // the shared project
const KC_INSTALL = 'blogpulse-install-id';
// Other secrets (settings blueprint, Step 7): each its own Keychain entry, typed into a native secure prompt, never in settings.json or the page.
const SECRETS = { jina: { key: "BLOGPULSE_JINA_KEY", name: "Jina Reader key", hint: "Free at jina.ai (API key). Only needed when Jina Reader answers 401, 402 or 403 without one." } };
const secretFor = id => Keychain.contains(SECRETS[id].key) ? Keychain.get(SECRETS[id].key) : null;
async function askSecret(id) {
const d = SECRETS[id], cur = secretFor(id);
const al = new Alert();
al.title = d.name;
al.message = (cur ? `The saved key ends in …${cur.slice(-4)}. Paste a new key to replace it. ` : "") + d.hint + " Stored in the iOS Keychain on this device only.";
al.addSecureTextField("Key", "");
al.addAction("Save key");
al.addCancelAction("Cancel");
if (await al.present() !== 0) return false;
const v = al.textFieldValue(0).trim();
if (!v) return false;
Keychain.set(d.key, v);
return true;
}
// ───────── Blueprints ─────────
// Shared blueprints this app was built with. One line per blueprint, in this exact shape:
// inventory tools read it without running the script, and Settings › Built with shows it.
const BLUEPRINTS = [
{ id: 'stability-patterns', name: 'Stability patterns', version: '1.0.2', since: '1.23.0' },
{ id: 'in-app-updates', name: 'In-app updates', version: '1.1.1', since: '1.23.0' },
{ id: 'settings', name: 'Settings', version: '2.0.1', since: '1.23.0' },
{ id: 'ai-configuration', name: 'AI configuration', version: '1.0.2', since: '1.23.0' },
{ id: 'launch-screen', name: 'Launch screen', version: '1.0.2', since: '1.23.0' },
{ id: 'widgets', name: 'Widgets', version: '1.1.1', since: '1.22.0' },
{ id: 'ai-invitation', name: 'AI invitation', version: '1.2.2', since: '1.23.0' },
{ id: 'audio-playback', name: 'Sound in silent mode', version: '1.0.2', since: '1.23.0' },
{ id: 'read-aloud', name: 'Read aloud', version: '1.2.4', since: '1.23.0' },
{ id: 'usage-analytics', name: 'Anonymous usage analytics', version: '1.1.1', since: '1.23.0' },
];
// What each blueprint is, shown when a Built with row is tapped (settings blueprint, Step 9).
// Written by `node tools/about.js` in app-blueprints from the versions in BLUEPRINTS; never edit by hand.
const BLUEPRINT_ABOUT = {
'stability-patterns': { what: "The rules that keep the app opening on any iPhone.", does: "Uses iCloud only when this iPhone has it, keeps data on the phone otherwise, and checks the Keychain before reading from it.", drives: "Where the app keeps its data, the widget, the installer and in-app updates.", why: "A new phone, one without iCloud or one with nothing saved yet still opens the app, instead of stopping with an error." },
'in-app-updates': { what: "The way the app offers and installs its own new versions.", does: "When the app opens it checks for a newer version, shows its three best features, and installs it with Update now; Later waits two days.", drives: "The update sheet, Settings › Updates and the installer.", why: "Fixes and features reach you without reinstalling by hand, and the app only replaces itself with a checked, newer copy." },
'settings': { what: "The shared Settings sheet every app has.", does: "Keeps the app's look, behaviour and limits in one place; changes apply at once and survive updates.", drives: "Appearance (colours, layout, text size, font), the app's own choices, Updates, every adjustable value, and this Built with list.", why: "Nobody edits code to change a setting, and every app is set up the same familiar way." },
'ai-configuration': { what: "How the app connects to Claude or OpenAI.", does: "Keeps your key in the iPhone Keychain, lets you pick the provider and model, tests the connection and counts the tokens each feature uses.", drives: "Settings › AI settings, every AI feature, and the ✦ AI label on everything AI wrote.", why: "Your key goes only to its own provider, you can see what AI uses, and the app still works without a key." },
'launch-screen': { what: "The branded screen the app opens on.", does: "Shows the app's logo, name and tagline for about two and a half seconds; a tap skips it, and Reduce Motion keeps it still.", drives: "The first moment after the app opens, with the same logo as the icon and the widget.", why: "The app starts the same recognisable way every time while its page gets ready behind the screen, and the screen can never get stuck." },
'widgets': { what: "The shared design for the app's Home Screen and Lock Screen widgets.", does: "Draws the app's logo and name, one headline figure or title, a few rows and an updated line, from the app's own data.", drives: "Every widget size, the Lock Screen versions, and the widget's settings.", why: "Widgets name their app, look like one family, say when their data is old, and never show a script error." },
'ai-invitation': { what: "A short card that shows what AI adds to this app.", does: "While no AI key is set, it names three things AI can do here and takes you straight to adding a key; it comes back every few days at most, and Don't remind me again ends it.", drives: "The invitation at launch, and the hand-over to Settings › AI settings.", why: "Features that need a key are hidden without one, so they are easy to miss; this shows them without nagging or covering anything else." },
'audio-playback': { what: "The rule that lets sound you asked for play with the Ring/Silent switch on.", does: "While the app reads, speaks or plays a sound you started, it tells iOS it is a media player, and gives sound back to other apps when it stops.", drives: "Reading aloud, spoken words, timer beeps and any other sound the app makes.", why: "Without it, iOS silently mutes the app while it looks as if it is playing." },
'read-aloud': { what: "The shared way the app reads text aloud, with an optional reader for articles.", does: "Reads posts, summaries or stories with an iPhone or AI voice, highlights the sentence being read, and shows how much is left.", drives: "The Listen buttons, the player at the bottom, the text view, the reader and Settings › Listening.", why: "You can listen hands-free and always know what is being read, from where, and for how long." },
'usage-analytics': { what: "Optional, anonymous counts of which features get used.", does: "Only after you say yes, it sends counts and fixed choices, never names, text, links or keys; turning it off stops sending and forgets the install ID.", drives: "The one-time question on the main page and Settings › Privacy.", why: "It shows what to improve next without collecting anything personal." },
};
// ---------- config ----------
const APP = "BlogPulse";
const SCHEME = "blogpulse://";
const AI = {
anthropic: { key: "BLOGPULSE_ANTHROPIC_KEY", model: "claude-haiku-5-5" },
openai: { key: "BLOGPULSE_OPENAI_KEY", model: "gpt-4o-mini" },
};
// ───────── AI invitation (app-blueprints · ai-invitation) ─────────
// What the invitation promises. Exactly three perks, each a real feature that needs a key.
const AI_INVITE = {
title: "Give BlogPulse superpowers", // punchy, names the app, at most 32 characters
perks: [ // icon + at most 48 characters each
{ icon: "✦", text: "A one-line summary on every new post" },
{ icon: "📰", text: "Your latest posts blended into one Story" },
{ icon: "⚡", text: "TL;DRs that say why each post matters" },
],
};
const DAY = 864e5;
const DEFAULT_UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1 BlogPulse/1.0";
// Everything tunable lives here; the Settings screen edits these (stored in settings.cfg, defaults below).
const CONFIG = [
["Checking blogs", [
{ k: "fetchTimeout", label: "Time limit per blog", help: "How long to wait for one blog before giving up", unit: "s", def: 15, min: 5, max: 60, step: 1 },
{ k: "pullHold", label: "Pull-to-refresh hold", help: "After pulling the list down, hold this long to check for new posts; 0 checks as soon as you let go", unit: "s", def: 1.5, min: 0, max: 5, step: 0.5 },
{ k: "concurrency", label: "Blogs checked at once", help: "Higher is faster but heavier on the network", unit: "", def: 6, min: 1, max: 12, step: 1 },
{ k: "userAgent", label: "Browser identity", help: "The User-Agent sent to blogs; some sites block unknown readers", type: "text", def: DEFAULT_UA },
]],
["Keeping posts", [
{ k: "maxAgeDays", label: "Keep posts for", help: "Older posts are removed unless you rated them", unit: "days", def: 90, min: 7, max: 365, step: 7 },
{ k: "maxArticles", label: "Keep at most", help: "Rated posts are kept first, then the newest", unit: "posts", def: 2000, min: 200, max: 10000, step: 100 },
{ k: "seedFreshDays", label: "New blog backlog", help: "When you follow a blog, posts older than this arrive already read", unit: "days", def: 3, min: 0, max: 30, step: 1 },
{ k: "pageSize", label: "Posts per page", help: "Shown before the Show more button", unit: "posts", def: 250, min: 50, max: 1000, step: 50 },
]],
["Picks", [
{ k: "picksMinRatings", label: "Ratings before Picks starts", unit: "ratings", def: 4, min: 1, max: 50, step: 1 },
{ k: "picksThreshold", label: "Picks strictness", help: "Higher means fewer, closer matches", unit: "", def: 0.8, min: 0.2, max: 3, step: 0.1 },
]],
["Categories", [
{ k: "kwStrictness", label: "Keyword strictness", help: "Without AI: how strong a keyword match must be to move a post out of its blog's usual topic", unit: "", def: 2.5, min: 1, max: 8, step: 0.5 },
]],
["AI limits", [
{ k: "aiBatch", label: "New posts summarised per check", unit: "posts", def: 25, min: 5, max: 50, step: 5 },
{ k: "aiBackfillDays", label: "Also sort unsorted posts from the last", help: "0 turns this off", unit: "days", def: 14, min: 0, max: 60, step: 1 },
{ k: "excerptChars", label: "Excerpt kept per post", help: "Text the Story and invites can draw on; applies to newly found posts", unit: "chars", def: 600, min: 200, max: 1500, step: 100 },
{ k: "tldrChars", label: "Article text sent for a TL;DR", unit: "chars", def: 9000, min: 2000, max: 30000, step: 1000 },
{ k: "storyMaxPosts", label: "Posts per Story", unit: "posts", def: 40, min: 5, max: 80, step: 5 },
{ k: "storyFallbackDays", label: "“Since last visit” fallback", help: "If little is new, Story uses unread posts from this many days", unit: "days", def: 2, min: 1, max: 14, step: 1 },
]],
["Widget", [
{ k: "widgetRefreshMin", label: "Ask iOS to refresh every", help: "iOS decides the exact timing", unit: "min", def: 30, min: 15, max: 240, step: 15 },
{ k: "widgetStaleMin", label: "Mark the widget as out of date after", help: "Older data shows \"Updated …\" in amber", unit: "min", def: 720, min: 60, max: 2880, step: 60 },
{ k: "widgetScanAfterMin", label: "Widget checks blogs if the last check is older than", unit: "min", def: 30, min: 10, max: 720, step: 10 },
{ k: "widgetScanBudget", label: "Time the widget may spend checking", unit: "s", def: 18, min: 5, max: 25, step: 1 },
{ k: "widgetStoryHours", label: "Show the AI story summary if newer than", unit: "h", def: 48, min: 1, max: 168, step: 1 },
]],
["Invites", [
{ k: "invitePresets", label: "Quick instructions", help: "One per line; shown as chips in the invite composer", type: "lines", def: ["Short and casual", "For my team on Slack", "For an executive: lead with business impact", "As a LinkedIn post", "Ask what they think"] },
]],
];
const CFG_FLAT = CONFIG.flatMap(([, items]) => items);
const cfgDef = k => CFG_FLAT.find(x => x.k === k);
const cfg = k => { const v = settings.cfg && settings.cfg[k]; return v === undefined ? cfgDef(k).def : v; };
function setCfg(k, v) {
const d = cfgDef(k);
if (!d) return;
settings.cfg = settings.cfg || {};
if (v === null) { delete settings.cfg[k]; return; }
if (d.type === "text") v = String(v || "").trim() || d.def;
else if (d.type === "lines") { v = String(Array.isArray(v) ? v.join("\n") : v || "").split("\n").map(x => x.trim()).filter(Boolean).slice(0, 20); if (!v.length) v = d.def; }
else {
v = Number(String(v).replace(",", "."));
if (!isFinite(v)) v = d.def;
v = Math.min(d.max, Math.max(d.min, v));
v = d.step < 1 ? Math.round(v / d.step) * d.step : Math.round(v);
v = Number(v.toFixed(2));
}
if (JSON.stringify(v) === JSON.stringify(d.def)) delete settings.cfg[k]; else settings.cfg[k] = v;
}
const PALETTES = {
ink: { paper: "#f6f7f9", sheet: "#ffffff", ink: "#0f172a", ink2: "#334155", muted: "#5b6475", rule: "#dde2ea", signal: "#1d4ed8", signalWash: "#e5edff", amber: "#b45309", amberWash: "#fdf0dc", danger: "#b91c1c", scheme: "light" },
sepia: { paper: "#f3ead6", sheet: "#fbf5e6", ink: "#2a1f14", ink2: "#4b3b2a", muted: "#73604a", rule: "#e1d3b5", signal: "#8a3b12", signalWash: "#f3dfc8", amber: "#a16207", amberWash: "#f6e5bf", danger: "#9f1239", scheme: "light" },
mint: { paper: "#f1f6f3", sheet: "#ffffff", ink: "#0d2318", ink2: "#2c4a3b", muted: "#556d60", rule: "#d3e2d9", signal: "#15803d", signalWash: "#dcf3e4", amber: "#b45309", amberWash: "#fbeed8", danger: "#b91c1c", scheme: "light" },
contrast: { paper: "#ffffff", sheet: "#ffffff", ink: "#000000", ink2: "#111111", muted: "#333333", rule: "#9a9a9a", signal: "#0033cc", signalWash: "#e0e8ff", amber: "#7a4b00", amberWash: "#ffeec2", danger: "#a30000", scheme: "light" },
slate: { paper: "#1c2128", sheet: "#22272e", ink: "#e6edf3", ink2: "#c5ced8", muted: "#9aa5b1", rule: "#373e47", signal: "#6cb6ff", signalWash: "#1d3350", amber: "#e3b341", amberWash: "#3a2f12", danger: "#ff8a7a", scheme: "dark" },
night: { paper: "#05070b", sheet: "#0f141c", ink: "#f3f6fa", ink2: "#d0d7e1", muted: "#9aa4b2", rule: "#1f2733", signal: "#7ab4ff", signalWash: "#132640", amber: "#f5c04a", amberWash: "#2d240c", danger: "#ff8f7a", scheme: "dark" },
};
// Categories: [id, label, colour, keyword pattern]. AI picks one of these ids; without AI the keywords decide.
const CATS = [
["tech", "Tech", "#3b82f6", /\b(software|engineer(ing)?|api|apis|kubernetes|k8s|cloud|database|postgres|java|jvm|kotlin|python|javascript|typescript|rust|golang|devops|infrastructure|latency|microservices?|frontend|backend|open[- ]source|github|servers?|deploy(ment)?|compiler|security|vulnerabilit(y|ies)|cve|linux|spring boot|aws|azure|gcp|sdk|developers?|programming|code ?base|observability)\b/gi],
["ai", "AI", "#8b5cf6", /\b(ai|a\.i\.|llms?|gpt-?\d*|genai|generative|machine learning|ml|neural|transformers?|agents?|agentic|inference|fine-?tun(e|ing)|embeddings?|rag|diffusion|chatbots?|claude|gemini|openai|anthropic|deepmind|copilot|prompt(s|ing)?)\b/gi],
["finance", "Finance", "#10b981", /\b(finance|financial|banks?|banking|payments?|stocks?|markets?|invest(ing|ment|ors?)?|funds?|crypto|bitcoin|interest rates?|inflation|earnings|ipo|fintech|trading|portfolios?|etfs?|bonds?|insurance|insurers?|fed|central bank|valuation|dividends?)\b/gi],
["business", "Business", "#f59e0b", /\b(startups?|ceo|cfo|acquisitions?|acquires?|mergers?|layoffs?|hiring|revenue|profits?|customers?|enterprise|retail|marketing|sales|leadership|strategy|growth|funding round|series [abc])\b/gi],
["health", "Health & Medicine", "#ef4444", /\b(health|healthcare|medical|medicine|clinical|patients?|diseases?|drugs?|fda|vaccines?|hospitals?|doctors?|cancer|diabetes|therap(y|ies)|biotech|genom(e|ics)|mental health|nutrition|fitness|surgery|pharma)\b/gi],
["science", "Science", "#06b6d4", /\b(research(ers)?|scientists?|physics|chemistry|biology|space|nasa|esa|astronom(y|ers)|climate|quantum|experiments?|universe|planets?|fusion|telescope|species)\b/gi],
["fashion", "Fashion & Style", "#ec4899", /\b(fashion|runway|couture|clothing|outfits?|luxury|beauty|makeup|skincare|vogue|apparel|sneakers?|wardrobe|menswear|womenswear|stylists?)\b/gi],
["design", "Design", "#f97316", /\b(design(ers)?|ux|ui|typography|figma|branding|illustration|interfaces?|usability|accessibility)\b/gi],
["world", "World & Politics", "#64748b", /\b(elections?|government|polic(y|ies)|president|ministers?|war|eu|regulation|regulators?|laws?|courts?|senate|parliament|sanctions?|geopolitic(s|al)|tariffs?)\b/gi],
["sports", "Sports", "#22c55e", /\b(football|soccer|nba|nfl|tennis|olympics?|league|championship|athletes?|formula 1|f1|marathon|cycling|world cup|transfer window)\b/gi],
["culture", "Culture", "#a855f7", /\b(films?|movies?|music|albums?|books?|novels?|art|museums?|tv series|theat(er|re)|video games?|gaming|celebrit(y|ies)|festival)\b/gi],
["other", "Other", "#94a3b8", null],
];
const CAT_IDS = CATS.map(c => c[0]);
function kwClassify(title, text) {
let best = "", bestScore = 0;
for (const [id, , , re] of CATS) {
if (!re) continue;
const t = (String(title).match(re) || []).length, b = (String(text).match(re) || []).length;
const score = t * 2 + Math.min(b, 6) * 0.6 * (id === "business" || id === "design" ? 0.7 : 1);
if (score > bestScore) { best = id; bestScore = score; }
}
return { cat: best, score: bestScore };
}
const CATALOG = [
["Netflix TechBlog", "https://netflixtechblog.com/feed", "streaming infrastructure data java"],
["Cloudflare Blog", "https://blog.cloudflare.com/rss/", "network security edge"],
["GitHub Blog", "https://github.blog/feed/", "devtools copilot ai"],
["Engineering at Meta", "https://engineering.fb.com/feed/", "infrastructure ai"],
["AWS News Blog", "https://aws.amazon.com/blogs/aws/feed/", "cloud"],
["Stripe Blog", "https://stripe.com/blog/feed.rss", "payments fintech api"],
["Spotify Engineering", "https://engineering.atspotify.com/feed/", "backstage platform"],
["Airbnb Engineering", "https://medium.com/feed/airbnb-engineering", "data mobile"],
["Pinterest Engineering", "https://medium.com/feed/pinterest-engineering", "ml data"],
["Dropbox Tech", "https://dropbox.tech/feed", "infrastructure storage"],
["Slack Engineering", "https://slack.engineering/feed/", "backend reliability"],
["Shopify Engineering", "https://shopify.engineering/blog.atom", "commerce ruby scale"],
["Microsoft DevBlogs", "https://devblogs.microsoft.com/feed/", "dotnet azure"],
["Spring Blog", "https://spring.io/blog.atom", "java spring boot"],
["JetBrains Blog", "https://blog.jetbrains.com/feed/", "java kotlin ide"],
["Docker Blog", "https://www.docker.com/blog/feed/", "containers"],
["Kubernetes Blog", "https://kubernetes.io/feed.xml", "cloud native"],
["Hugging Face Blog", "https://huggingface.co/blog/feed.xml", "ai ml llm", "ai"],
["OpenAI News", "https://openai.com/news/rss.xml", "ai llm", "ai"],
["Google DeepMind", "https://deepmind.google/blog/rss.xml", "ai research", "ai"],
["Martin Fowler", "https://martinfowler.com/feed.atom", "architecture refactoring"],
["InfoQ", "https://feed.infoq.com/", "architecture java enterprise"],
["Vercel", "https://vercel.com/atom", "frontend nextjs"],
];
// ---------- pure helpers (no Scriptable APIs) ----------
const hash = s => { let h = 5381; for (let i = 0; i < s.length; i++) h = ((h << 5) + h + s.charCodeAt(i)) | 0; return (h >>> 0).toString(36); };
const ENT = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", hellip: "…", mdash: "—", ndash: "–", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“", copy: "©" };
function decode(s) {
return String(s).replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
if (e[0] === "#") {
const c = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
try { return String.fromCodePoint(c); } catch (_) { return m; }
}
return ENT[e.toLowerCase()] ?? m;
});
}
const cdata = s => String(s).replace(/<!\[CDATA\[([\s\S]*?)\]\]>/g, "$1");
const stripTags = s => s.replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ").replace(/<[^>]+>/g, " ");
function toText(s, max) {
if (!s) return "";
let t = decode(stripTags(decode(stripTags(cdata(s))))).replace(/\s+/g, " ").trim();
t = t.replace(/The post .{0,240}? appeared first on .{0,160}$/i, "")
.replace(/(Continue reading|Read more)\s*(on Medium)?\s*[»›…]*\s*$/i, "").trim();
if (max && t.length > max) {
t = t.slice(0, max);
t = t.slice(0, Math.max(t.lastIndexOf(" "), max - 25)).replace(/[,;:.\s]+$/, "") + "…";
}
return t;
}
function tag(block, names) {
for (const n of names) {
const m = block.match(new RegExp(`<${n}(?:\\s[^>]*)?>([\\s\\S]*?)</${n}>`, "i"));
if (m && m[1].trim()) return m[1];
}
return "";
}
function attr(t, name) {
const m = t.match(new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, "i"));
return m ? decode(m[1] ?? m[2] ?? m[3] ?? "") : "";
}
const originOf = u => (String(u).match(/^https?:\/\/[^\/?#]+/i) || [""])[0];
const hostOf = u => originOf(u).replace(/^https?:\/\/(www\.)?/i, "");
function resolve(base, href) {
href = String(href || "").trim();
if (/^https?:\/\//i.test(href)) return href;
const m = String(base || "").match(/^(https?):\/\/([^\/?#]+)([^?#]*)/i);
if (!m || !href) return href;
if (href.startsWith("//")) return m[1] + ":" + href;
if (href.startsWith("/")) return `${m[1]}://${m[2]}${href}`;
return `${m[1]}://${m[2]}${(m[3] || "/").replace(/[^\/]*$/, "")}${href}`;
}
const catalogCat = feed => { const c = CATALOG.find(x => x[1] === feed || hostOf(x[1]) === hostOf(feed)); return c ? (c[3] || "tech") : ""; };
const looksLikeFeed = t => /<(rss|feed|rdf:RDF)[\s>]/i.test(String(t).slice(0, 4000));
function parseFeed(xml, base) {
const atom = /<feed[\s>]/i.test(xml.slice(0, 4000)) && !/<rss[\s>]/i.test(xml.slice(0, 4000));
const head = xml.split(atom ? /<entry[\s>]/i : /<item[\s>]/i)[0];
const title = toText(tag(head, ["title"]), 120);
let site = "";
if (atom) {
for (const l of head.match(/<link\b[^>]*>/gi) || []) {
const rel = attr(l, "rel");
if (!rel || rel === "alternate") { site = attr(l, "href"); break; }
}
} else site = toText(tag(head, ["link"]));
const items = [];
for (const b of xml.match(atom ? /<entry[\s>][\s\S]*?<\/entry>/gi : /<item[\s>][\s\S]*?<\/item>/gi) || []) {
let link = "";
if (atom) {
const ls = b.match(/<link\b[^>]*>/gi) || [];
const alt = ls.find(l => !attr(l, "rel") || attr(l, "rel") === "alternate") || ls[0];
link = alt ? attr(alt, "href") : "";
} else {
link = toText(tag(b, ["link"]));
if (!link) { const g = toText(tag(b, ["guid"])); if (/^https?:/i.test(g)) link = g; }
}
if (link) link = resolve(base, link);
const t = toText(tag(b, ["title"]), 300);
if (!t && !link) continue;
const summary = tag(b, ["description", "summary"]);
const full = tag(b, ["content:encoded", "content"]);
const d = new Date(toText(tag(b, ["pubDate", "published", "updated", "dc:date", "issued"])));
let desc = toText(summary || full, 260);
if (desc === t) desc = toText(full, 260) === t ? "" : toText(full, 260);
items.push({
guid: toText(tag(b, ["guid", "id"])) || link || t,
title: t || "(untitled)", link, desc,
body: toText(full || summary, 1500),
pub: isNaN(d) ? 0 : d.getTime(),
});
}
return { title, site: site ? resolve(base, site) : "", items };
}
async function pool(items, n, fn) {
const out = new Array(items.length); let i = 0;
await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
while (i < items.length) { const k = i++; try { out[k] = await fn(items[k], k); } catch (e) { out[k] = null; } }
}));
return out;
}
const STOP = new Set("the and for with from into your you our are was were this that what how why when new using use via about over more than their its have has will can not but all out just how-to part introducing announcing".split(" "));
const toks = s => [...new Set((String(s).toLowerCase().match(/[a-z0-9][a-z0-9+#.-]{2,}/g) || []).map(w => w.replace(/[.-]+$/, "")).filter(w => w.length > 2 && !STOP.has(w)))];
function computePicks(list, minN = 4, thr = 0.8) {
const rated = list.filter(a => a.rating);
if (rated.length < minN) return { ready: false, n: rated.length, picks: {} };
const bySrc = {}, kw = {};
for (const a of rated) {
const w = a.rating - 2; // ★ = -1, ★★ = 0, ★★★ = +1
(bySrc[a.src] = bySrc[a.src] || []).push(w);
for (const t of toks(a.title)) kw[t] = (kw[t] || 0) + w;
}
const srcScore = {};
for (const k in bySrc) { const v = bySrc[k]; srcScore[k] = (v.reduce((x, y) => x + y, 0) / v.length) * Math.min(1, v.length / 3); }
const picks = {};
for (const a of list) {
if (a.read || a.rating) continue;
const ts = toks(a.title);
const k = ts.reduce((s, t) => s + (kw[t] || 0), 0) / Math.sqrt(ts.length || 1);
const score = (srcScore[a.src] || 0) + 0.6 * k;
if (score >= thr) picks[a.id] = Math.round(score * 10) / 10;
}
return { ready: true, n: rated.length, picks };
}
// ---------- end pure helpers ----------
// ---------- storage ----------
// Stability patterns (app-blueprints · stability-patterns 1.0.0): iCloud only when this script itself lives in iCloud Drive.
// On a phone that isn't signed in to iCloud, the first call on Scriptable's iCloud manager ends the script
// ("iCloud is not supported"), and a try/catch doesn't reliably stop it: so there, iCloud is never touched.
const ICLOUD_OK = (() => { try { return /\/Mobile Documents\//.test(module.filename); } catch (e) { return false; } })();
function icloudFm() { // the iCloud manager, or null on a phone without iCloud
if (!ICLOUD_OK) return null;
try { const ic = FileManager.iCloud(); ic.documentsDirectory(); return ic; } catch (e) { return null; }
}
const scriptFm = (path) => (/\/Mobile Documents\//.test(path) && icloudFm()) || FileManager.local(); // where the running script lives (updates)
const fm = icloudFm() || FileManager.local(); // storage: iCloud Drive, or the phone
const DIR = fm.joinPath(fm.documentsDirectory(), APP);
if (!fm.fileExists(DIR)) fm.createDirectory(DIR, true);
const P = n => fm.joinPath(DIR, n + ".json");
const loadIssues = []; // files that didn't arrive (iCloud too slow, or unreadable): never written this run
const loadRepaired = []; // files that arrived damaged: kept aside as <name>.broken-<time>.json, then started fresh
async function load(n, def, waitMs = 10000) {
const p = P(n);
if (!fm.fileExists(p)) return def;
let txt;
try {
if (fm.isFileStoredIniCloud(p) && !fm.isFileDownloaded(p)) {
// iCloud can take a long time (or forever, offline): never let start-up hang on it
await Promise.race([fm.downloadFileFromiCloud(p), new Promise(r => Timer.schedule(waitMs, false, r))]);
if (!fm.isFileDownloaded(p)) { loadIssues.push(n); startLog(`iCloud didn't deliver ${n}.json in ${waitMs / 1000} s`); return def; }
}
txt = fm.readString(p);
} catch (e) { loadIssues.push(n); startLog(`Couldn't read ${n}.json: ${e}`); return def; } // not read: never saved over
try { return JSON.parse(txt); }
catch (e) { keepBroken(fm, p, n, txt); return def; }
}
// It arrived but is damaged: keep a copy next to it, then start this file fresh so saving can carry on (1.1.0).
// Without this, one damaged file stopped the app from ever saving again. The widget reads the data on every refresh
// and never saves, so a copy that's already there is not made again. The parse error isn't logged: it can quote the file.
function keepBroken(fm, p, n, txt) {
try {
const base = p.replace(/\.json$/, ""), dir = p.slice(0, p.lastIndexOf("/")), pre = base.slice(dir.length + 1) + ".broken-";
let kept = false;
try { kept = fm.listContents(dir).some(f => f.startsWith(pre) && fm.readString(fm.joinPath(dir, f)) === txt); } catch (_) {}
if (!kept) fm.writeString(base + ".broken-" + Date.now() + ".json", txt);
if (!loadRepaired.includes(n)) loadRepaired.push(n);
startLog(`${n}.json was damaged (not valid JSON); ${kept ? "a copy was already kept" : "kept a copy"} and started it fresh`);
} catch (e) { loadIssues.push(n); startLog(`${n}.json was damaged and couldn't be copied aside`); } // no copy, no overwrite
}
// Data files are only written once they were read, so a slow start can never save an empty list over them.
const write = (n, v) => {
if (n === "settings" ? !settingsOk : !dataLoaded) return;
fm.writeString(P(n), JSON.stringify(v));
};
// A short start-up log on the phone (local, not iCloud), shown if BlogPulse gets stuck while opening.
const LOG_PATH = FileManager.local().joinPath(FileManager.local().documentsDirectory(), "blogpulse-startup.log");
function startLog(msg) {
try {
const lfm = FileManager.local(), line = new Date().toISOString().slice(11, 19) + " " + msg;
const old = lfm.fileExists(LOG_PATH) ? lfm.readString(LOG_PATH).split("\n").slice(-60) : [];
lfm.writeString(LOG_PATH, old.concat(line).join("\n"));
} catch (e) {}
}
// Blogs, posts, stories and usage are read in loadData(): the app shows its first screen before
// reading them, because iCloud can be slow to hand files over (a black screen when opened from the widget).
let sources = [], articles = {}, stories = {}, dataLoaded = false;
async function loadData() {
loadIssues.length = 0; // loadRepaired is kept, so a damaged settings.json (read before this) still gets its toast
sources = await load("sources", []);
articles = await load("articles", {});
stories = await load("stories", {}); // AI story per "scope|category"
for (const k of Object.keys(stories)) if (!k.includes("|")) delete stories[k];
usage = await load("usage", usage);
dataLoaded = loadIssues.length === 0; // anything missing: show what we have, save nothing over it
}
const settings = Object.assign(
{ groupBy: "day", view: "unread", readOnOpen: false, openInReader: true, collapseRead: true, readerProxy: true, ai: true, aiProvider: "anthropic", lastSession: 0, lastScan: 0,
checkUpdates: true, // offer new versions from GitHub (asks again 2 days after "Later")
shareUsage: false, usageAsked: false, // anonymous usage counts: off until the person agrees
speechEngine: "device", ttsModel: "gpt-4o-mini-tts", ttsVoice: "coral", ttsInstructions: "", // read aloud: iPhone voices or OpenAI
theme: "auto", density: "comfortable", font: "sans", textSize: 1, storyScope: "new" },
await load("settings", {})
);
const settingsOk = !loadIssues.includes("settings"); // settings that were never read are never saved over
const prevSession = settings.lastSession || 0; // everything first seen after this is "new"
function saveAll(touchSession = true) {
if (touchSession && dataLoaded) settings.lastSession = Date.now();
write("sources", sources); write("articles", articles); // write() skips these until the data was read
write("settings", settings);
}
let usageQueue = [], usageTimer = null;
const usageAvailable = () => !!USAGE.KEY;
const usageOn = () => usageAvailable() && !!settings.shareUsage;
function installId() {
if (Keychain.contains(KC_INSTALL)) return Keychain.get(KC_INSTALL);
const id = UUID.string().toLowerCase();
Keychain.set(KC_INSTALL, id);
return id;
}
function track(event, props = {}) {
if (!usageOn()) return;
try {
usageQueue.push({ event, timestamp: new Date().toISOString(),
properties: Object.assign({ distinct_id: installId(), $process_person_profile: false, app: APP_ID, app_version: VERSION, $lib: APP_ID }, props) });
if (usageQueue.length >= 25) flushUsage();
else if (!usageTimer) usageTimer = Timer.schedule(3000, false, () => { usageTimer = null; flushUsage(); });
} catch (e) {}
}
let usageLast = null; // { at, events, ok, status, host, error }: shown in Settings › Privacy
async function postUsage(host, batch) {
const r = new Request(host + '/batch/');
r.method = 'POST'; r.timeoutInterval = 10; r.headers = { 'Content-Type': 'application/json' };
r.body = JSON.stringify({ api_key: USAGE.KEY, batch });
let body = '';
try { body = await r.loadString(); } catch (e) { return { ok: false, status: 0, host, error: String(e.message || e) }; }
const status = (r.response && r.response.statusCode) || 0;
return { ok: status >= 200 && status < 300, status, host, error: status >= 200 && status < 300 ? '' : String(body || '').slice(0, 200) };
}
// Sends what's queued in one request. Never slows the app; if it fails, those counts are gone (and the log says why).
async function flushUsage() {
if (!usageQueue.length) return usageLast;
if (!usageOn()) { usageQueue = []; return usageLast; }
const batch = usageQueue.splice(0, usageQueue.length);
const res = await postUsage(USAGE.HOST, batch);
usageLast = Object.assign({ at: Date.now(), events: batch.length }, res);
try { startLog(`usage: ${batch.length} event${batch.length === 1 ? '' : 's'} → ${res.ok ? 'sent to ' + res.host.replace('https://', '') : 'not sent: ' + (res.status ? 'HTTP ' + res.status + ' ' : '') + res.error}`); } catch (e) {}
return usageLast;
}
function usageStatus() {
const u = usageLast;
if (!u) return '';
const t = new Date(u.at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
return u.ok ? `Last sent ${t}: ${u.events} event${u.events === 1 ? '' : 's'}, accepted (${u.host.replace('https://', '')})`
: `Last try ${t} failed: ${u.status ? 'HTTP ' + u.status + ' ' : ''}${u.error}`;
}
function setUsage(on) {
settings.shareUsage = !!on; settings.usageAsked = true; saveAll();
if (on) track('usage_opt_in');
else { usageQueue = []; if (Keychain.contains(KC_INSTALL)) Keychain.remove(KC_INSTALL); } // a fresh ID if switched on again
}
// ---------- network ----------
async function fetchText(url, timeout = cfg("fetchTimeout")) {
const r = new Request(url);
r.timeoutInterval = timeout;
r.headers = { "User-Agent": cfg("userAgent"), "Accept": "application/rss+xml, application/atom+xml, application/xml;q=0.9, text/xml;q=0.9, text/html;q=0.8, */*;q=0.5" };
const text = await r.loadString();
const code = r.response && r.response.statusCode;
if (code && code >= 400) throw new Error(`HTTP ${code}`);
return { text: text || "", url: (r.response && r.response.url) || url };
}
function feedInfo(text, url) {
const f = parseFeed(text, url);
return f.items.length ? { feed: url, title: f.title || hostOf(url), site: f.site || originOf(url), count: f.items.length, latest: f.items[0].title } : null;
}
async function probe(u) {
try { const r = await fetchText(u, 10); return looksLikeFeed(r.text) ? feedInfo(r.text, r.url) : null; } catch (e) { return null; }
}
const COMMON_PATHS = ["/feed", "/rss", "/feed.xml", "/rss.xml", "/atom.xml", "/index.xml", "/feed/", "/blog/feed", "/blog/rss.xml", "/blog/feed.xml", "/blog/atom.xml", "/engineering/feed"];
async function discoverUrl(input) {
const url = /^https?:\/\//i.test(input) ? input : "https://" + input;
let page = null;
try { page = await fetchText(url, 12); } catch (e) {}
if (page && looksLikeFeed(page.text)) { const i = feedInfo(page.text, page.url); return i ? [i] : []; }
const cands = new Set();
if (page) {
for (const l of page.text.match(/<link\b[^>]*>/gi) || []) {
const type = attr(l, "type").toLowerCase(), rel = attr(l, "rel").toLowerCase();
if (rel.includes("alternate") && /(rss|atom)\+xml/.test(type) && attr(l, "href")) cands.add(resolve(page.url, attr(l, "href")));
}
}
if (!cands.size) {
const base = page ? page.url : url, o = originOf(base);
const p = base.slice(o.length).split(/[?#]/)[0].replace(/\/$/, "");
for (const c of COMMON_PATHS) { if (p) cands.add(o + p + c); cands.add(o + c); }
}
const found = (await pool([...cands].slice(0, 18), cfg("concurrency"), probe)).filter(Boolean);
const seen = new Set();
return found.filter(f => !seen.has(f.feed) && seen.add(f.feed));
}
async function searchFeeds(q) {
const ql = q.toLowerCase();
const local = CATALOG.filter(c => (c[0] + " " + c[2] + " " + c[1]).toLowerCase().includes(ql))
.map(c => ({ feed: c[1], title: c[0], desc: "Popular tech blog · " + c[2] }));
let remote = [];
try {
const r = new Request(`https://cloud.feedly.com/v3/search/feeds?query=${encodeURIComponent(q)}&count=20&locale=en`);
r.timeoutInterval = 12;
const j = await r.loadJSON();
remote = (j.results || []).filter(x => x.feedId && x.feedId.startsWith("feed/")).map(x => ({
feed: x.feedId.slice(5), title: x.title || hostOf(x.website || x.feedId.slice(5)),
desc: toText(x.description || "", 140), subs: x.subscribers || 0,
}));
} catch (e) {}
const seen = new Set();
return [...local, ...remote].filter(r => { const k = r.feed.toLowerCase().replace(/\/$/, ""); return !seen.has(k) && seen.add(k); });
}
function discover(q) {
q = q.trim();
const isUrl = /^https?:\/\//i.test(q) || /^[^\s\/]+\.[a-z]{2,}(\/\S*)?$/i.test(q);
return isUrl ? discoverUrl(q) : searchFeeds(q);
}
// ---------- articles ----------
function classifyKw(a) {
const r = kwClassify(a.title, (a.desc || "") + " " + (a.ex || ""));
a.kw = r.score >= cfg("kwStrictness") ? r.cat : ""; // strong signal: can override the blog's usual category
a.kw0 = r.cat || ""; // weak signal: only used to learn a blog's usual category
}
function sourceDefaults() {
const votes = {};
for (const a of Object.values(articles)) {
if (a.kw === undefined) classifyKw(a);
const c = a.kw || a.kw0; if (!c) continue;
const v = votes[a.src] = votes[a.src] || {}; v[c] = (v[c] || 0) + 1;
}
const out = {};
for (const s of sources) {
if (s.defCat === undefined) s.defCat = catalogCat(s.feed);
const v = votes[s.id] || {}, top = Object.keys(v).sort((x, y) => v[y] - v[x])[0];
out[s.id] = s.catLock || s.defCat || top || "other";
}
return out;
}
function catOf(a, defs) {
const s = sources.find(x => x.id === a.src) || {};
return s.catLock || a.aiCat || a.kw || defs[a.src] || "other";
}
function ingest(src, items, seeding) {
const now = Date.now(), cutoff = now - cfg("maxAgeDays") * DAY, fresh = [];
for (const it of items) {
const id = hash(src.id + "|" + it.guid);
if (articles[id]) continue;
const pub = it.pub && it.pub <= now + DAY ? it.pub : now;
if (pub < cutoff) continue;
const a = { id, src: src.id, title: it.title, link: it.link, desc: it.desc, pub, seen: now };
if (seeding && now - pub > cfg("seedFreshDays") * DAY) { a.seeded = 1; a.read = 1; }
else if (it.body) a.ex = it.body.slice(0, cfg("excerptChars")); // excerpt kept for the AI story
classifyKw(a);
articles[id] = a;
if (!a.seeded) fresh.push({ a, body: it.body });
}
return fresh;
}
function prune() {
const cutoff = Date.now() - cfg("maxAgeDays") * DAY, ids = new Set(sources.map(s => s.id));
// Read later and rated posts are never dropped for age, and are kept first when trimming
let list = Object.values(articles).filter(a => ids.has(a.src) && (a.rating || a.pinned || a.pub >= cutoff));
const keepFirst = a => (a.pinned ? 2 : 0) + (a.rating ? 1 : 0);
if (list.length > cfg("maxArticles")) list = list.sort((x, y) => keepFirst(y) - keepFirst(x) || y.pub - x.pub).slice(0, cfg("maxArticles"));
articles = Object.fromEntries(list.map(a => [a.id, a]));
}
async function addSource(feedUrl, titleHint, depth = 0) {
const r = await fetchText(feedUrl, 15);
if (!looksLikeFeed(r.text)) {
if (depth) throw new Error("No feed found at that address");
const d = await discoverUrl(feedUrl);
if (!d.length) throw new Error("No RSS or Atom feed found at that address");
return addSource(d[0].feed, titleHint, 1);
}
if (sources.some(s => s.feed === r.url || s.feed === feedUrl)) throw new Error("You already follow this blog");
const f = parseFeed(r.text, r.url);
if (!f.items.length) throw new Error("The feed has no articles yet");
const src = { defCat: catalogCat(feedUrl) || catalogCat(r.url), id: hash(r.url), title: titleHint || (f.title || "").replace(/\s+[-–—|]\s+Medium$/i, "") || hostOf(r.url), feed: r.url, site: f.site || originOf(r.url), added: Date.now(), lastFetched: Date.now() };
sources.push(src);
const fresh = ingest(src, f.items, true);
return { src, count: f.items.length, fresh };
}
async function scanAll(onProgress) {
const active = sources.filter(s => !s.paused);
let done = 0; const fresh = [];
await pool(active, cfg("concurrency"), async s => {
try {
const r = await fetchText(s.feed);
if (!looksLikeFeed(r.text)) throw new Error("Feed address no longer returns a feed");
fresh.push(...ingest(s, parseFeed(r.text, r.url).items, false));
s.lastFetched = Date.now(); s.err = null;
} catch (e) { s.err = String(e.message || e).slice(0, 120); }
onProgress(++done, active.length);
});
prune();
settings.lastScan = Date.now();
return fresh;
}
// ---------- optional AI summaries ----------
const PROVIDERS = { anthropic: "Claude", openai: "OpenAI" };
const keyFor = p => Keychain.contains(AI[p].key) ? Keychain.get(AI[p].key) : null;
const aiKey = () => keyFor(settings.aiProvider);
const modelFor = p => (settings.model && settings.model[p]) || AI[p].model;
const maskKey = k => k ? (k.length > 14 ? k.slice(0, 7) + "…" + k.slice(-4) : "…" + k.slice(-4)) : null;
// token usage, kept per provider, model, feature and day
let usage = { since: Date.now(), p: {} }; // read in loadData()
const dayKey = (d = new Date()) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
function recordUsage(provider, model, feature, tin, tout, chars = 0) { // chars: text sent for speech
const P = usage.p[provider] = usage.p[provider] || { calls: 0, in: 0, out: 0, models: {}, features: {}, days: {} };
const b = (o, k) => o[k] = o[k] || { calls: 0, in: 0, out: 0 };
for (const x of [P, b(P.models, model), b(P.features, feature), b(P.days, dayKey())]) { x.calls++; x.in += tin; x.out += tout; if (chars) x.chars = (x.chars || 0) + chars; }
const days = Object.keys(P.days).sort();
while (days.length > 400) delete P.days[days.shift()];
write("usage", usage);
}
async function fetchModels(p) {
const key = keyFor(p);
if (!key) throw new Error(`Add a ${PROVIDERS[p]} key first`);
const r = new Request(p === "openai" ? "https://api.openai.com/v1/models" : "https://api.anthropic.com/v1/models?limit=100");
r.headers = p === "openai" ? { "Authorization": "Bearer " + key } : { "x-api-key": key, "anthropic-version": "2023-06-01" };
r.timeoutInterval = 20;
const j = await r.loadJSON();
if (j.error) throw new Error(j.error.message || "Couldn't load models");
let list = (j.data || []).map(m => ({ id: m.id, name: m.display_name || m.id, t: m.created_at ? Date.parse(m.created_at) : (m.created || 0) * 1000 }));
if (p === "openai") { // speech models get their own list, for Settings › Listening
settings.ttsModels = { at: Date.now(), list: list.filter(m => /tts/.test(m.id)).sort((a, b) => b.t - a.t).map(m => ({ id: m.id, name: m.id })) };
}
if (p === "openai") list = list.filter(m => /^(gpt-|o\d|chatgpt-)/.test(m.id) && !/(audio|realtime|tts|transcribe|image|search|embedding|instruct|moderation)/.test(m.id));
list.sort((a, b) => b.t - a.t);
settings.models = settings.models || {};
settings.models[p] = { at: Date.now(), list: list.map(m => ({ id: m.id, name: m.name })) };
return list.length;
}
async function askKey(p) {
const cur = keyFor(p);
const al = new Alert();
al.title = `${PROVIDERS[p]} API key`;
al.message = cur ? `The saved key ends in …${cur.slice(-4)}. Paste a new key to replace it.` : "Paste your API key. It's stored in the iOS Keychain on this device only.";
al.addSecureTextField(p === "openai" ? "sk-…" : "sk-ant-…", "");
al.addAction("Save key");
al.addCancelAction("Cancel");
if (await al.present() !== 0) return false;
const v = al.textFieldValue(0).trim();
if (!v) return false;
Keychain.set(AI[p].key, v);
if (!aiKey()) settings.aiProvider = p;
return true;
}
// AI invitation: when it may appear. Its state lives in settings.json as settings.aiInvite (no UI of its own).
// Not to be confused with "Invite someone to read a post" (makeInvite, the "invite" action), which is a feature.
const INVITE_DAY = 864e5;
const INVITE_GAP = 3; // days between invitations (about twice a week)
const INVITE_GAP_SLOW = 7; // days between invitations after the 4th "Later"
function aiInviteDue(now = Date.now()) {
const s = settings.aiInvite || (settings.aiInvite = {});
if (aiKey()) return false; // a key means AI is on: nothing to invite to
if (s.off) return false; // "Don't remind me again"
return now >= (s.next || 0); // from the very first launch (right after install), then at most every 3 days
}
// Removing the last key turns AI off: invite again from the next launch (called in the "airm" action).
function aiInviteKeyRemoved() {
if (aiKey()) return;
const s = settings.aiInvite || (settings.aiInvite = {});
s.next = 0; saveAll();
}
// The page reports what happened: "shown", "open", "later" or "never".
function aiInviteNote(what, now = Date.now()) {
const s = settings.aiInvite || (settings.aiInvite = {});
if (what === "shown") { s.shown = (s.shown || 0) + 1; s.next = now + INVITE_GAP * INVITE_DAY; }
else if (what === "later") { s.later = (s.later || 0) + 1; s.next = now + (s.later >= 4 ? INVITE_GAP_SLOW : INVITE_GAP) * INVITE_DAY; }
else if (what === "never") s.off = true;
else return; // "open": the AI sheet takes over; "shown" already set the next date
saveAll();
}
async function aiCall(system, user, maxTokens = 2500, feature = "other", provider = settings.aiProvider) {
const key = keyFor(provider);
if (!key) throw new Error(`No ${PROVIDERS[provider]} key saved`);
const openai = provider === "openai", model = modelFor(provider);
const r = new Request(openai ? "https://api.openai.com/v1/chat/completions" : "https://api.anthropic.com/v1/messages");
r.method = "POST";
r.timeoutInterval = 90;
if (openai) {
r.headers = { "Authorization": "Bearer " + key, "Content-Type": "application/json" };
r.body = JSON.stringify({ model, messages: [{ role: "system", content: system }, { role: "user", content: user }] });
} else {
r.headers = { "x-api-key": key, "anthropic-version": "2023-06-01", "content-type": "application/json" };
r.body = JSON.stringify({ model, max_tokens: maxTokens, system, messages: [{ role: "user", content: user }] });
}
const j = await r.loadJSON();
if (j.error) throw new Error(j.error.message || "AI request failed");
const u = j.usage || {};
recordUsage(provider, model, feature,
openai ? (u.prompt_tokens || 0) : (u.input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.cache_read_input_tokens || 0),
openai ? (u.completion_tokens || 0) : (u.output_tokens || 0));
return openai ? ((j.choices && j.choices[0] && j.choices[0].message.content) || "") : (j.content || []).map(c => c.text || "").join("");
}
function parseJSON(txt) {
const s = String(txt).replace(/```json|```/g, "").trim();
const a = s.search(/[\[{]/), b = Math.max(s.lastIndexOf("}"), s.lastIndexOf("]"));
return JSON.parse(s.slice(a, b + 1));
}
async function aiSummaries(fresh) {
if (!aiKey() || !settings.ai) return 0;
const ids = new Set(fresh.map(x => x.a.id));
const back = Object.values(articles).filter(a => !a.seeded && !a.aiCat && !ids.has(a.id) && a.pub > Date.now() - cfg("aiBackfillDays") * DAY)
.sort((a, b) => b.pub - a.pub).slice(0, cfg("aiBackfillDays") ? Math.max(0, cfg("aiBatch") + 5 - Math.min(fresh.length, cfg("aiBatch"))) : 0).map(a => ({ a, body: a.ex || a.desc }));
const batch = fresh.slice(0, cfg("aiBatch")).concat(back);
if (!batch.length) return 0;
const system = `You summarise and categorise blog posts for a senior software architect. For each numbered article: write one neutral sentence (max 30 words) saying what it covers and why it matters, and choose its category by the article's subject (not by who published it), exactly one of: ${CAT_IDS.join(", ")}. Reply with ONLY a JSON array like [{"i":0,"s":"...","c":"tech"}], no prose, no code fences.`;
const user = batch.map((x, i) => `[${i}] ${x.a.title}\n${x.body || x.a.desc}`).join("\n\n");
const arr = parseJSON(await aiCall(system, user, 2500, "summaries"));
let n = 0;
for (const o of Array.isArray(arr) ? arr : []) {
const x = batch[o.i]; if (!x) continue;
if (o.s && !x.a.ai) x.a.ai = String(o.s).slice(0, 300);
if (CAT_IDS.includes(o.c)) x.a.aiCat = o.c;
n++;
}
return n;
}
// ---------- AI story: the latest posts blended into one read ----------
function storyPool(scope, cat) {
const now = Date.now(), defs = sourceDefaults();
const list = Object.values(articles).filter(a => !a.seeded && (cat === "all" || catOf(a, defs) === cat)).sort((a, b) => b.pub - a.pub);
let pick;
if (scope === "today") pick = list.filter(a => a.pub >= now - DAY);
else if (scope === "week") pick = list.filter(a => a.pub >= now - 7 * DAY);
else {
pick = list.filter(a => a.seen > prevSession);
if (pick.length < 3) pick = list.filter(a => !a.read && a.pub >= now - cfg("storyFallbackDays") * DAY);
}
if (pick.length < 3) pick = list.slice(0, 12);
return pick.slice(0, cfg("storyMaxPosts"));
}
const storySig = (scope, cat) => hash(storyPool(scope, cat).map(a => a.id).join(","));
const storyKey = () => settings.storyScope + "|" + (settings.category || "all");
async function makeStory(scope, cat) {
const pool = storyPool(scope, cat);
if (!pool.length) throw new Error(cat === "all" ? "No posts to write about yet" : "No posts in this category yet");
const srcName = id => (sources.find(s => s.id === id) || {}).title || "";
const liked = Object.values(articles).filter(a => a.rating === 3).sort((a, b) => b.pub - a.pub).slice(0, 12).map(a => "- " + a.title);
const system = `You edit a personal tech briefing for a senior software architect. Blend the numbered posts into ONE readable story: group related posts into themes, explain what happened and why it matters, and connect posts from different companies only where they genuinely relate. Plain, direct language; no hype, no filler. Cite posts as [n] right after the sentence that uses them; every post you mention must be cited. Use only facts in the excerpts.
Reply with ONLY JSON, no code fences:
{"headline":"...","dek":"one-sentence overview","tldr":["3 bullet points, each one sentence with [n] citations"],"sections":[{"title":"...","body":"2-4 short paragraphs separated by a blank line"}],"mustRead":[{"n":0,"why":"one sentence"}]}
Use 3-6 sections and at most 3 mustRead posts.`;
const user = (liked.length ? `Posts the reader rated highest — favour similar themes:\n${liked.join("\n")}\n\n` : "") +
"Posts:\n\n" + pool.map((a, i) => `[${i}] ${a.title} — ${srcName(a.src)}, ${new Date(a.pub).toDateString()}\n${a.ex || a.ai || a.desc || ""}`).join("\n\n");
const j = parseJSON(await aiCall(system, user, 4000, "story"));
const ids = pool.map(a => a.id);
stories[scope + "|" + cat] = {
scope, cat, sig: storySig(scope, cat), at: Date.now(), ids,
headline: String(j.headline || "Your tech briefing"), dek: String(j.dek || ""), provider: settings.aiProvider,
tldr: (Array.isArray(j.tldr) ? j.tldr : []).map(String).slice(0, 5),
sections: (j.sections || []).map(x => ({ title: String(x.title || ""), body: String(x.body || "") })).filter(x => x.body),
mustRead: (j.mustRead || []).filter(x => ids[x.n]).map(x => ({ id: ids[x.n], why: String(x.why || "") })),
};
write("stories", stories);
}
// ---------- TL;DR for a single post: AI when a key is saved, otherwise extracted from the page ----------
function extractArticle(html) {
const meta = name => { const m = html.match(new RegExp(`<meta[^>]+(?:property|name)=["']${name}["'][^>]*>`, "i")); return m ? toText(attr(m[0], "content")) : ""; };
const desc = meta("og:description") || meta("description");
let h = html.replace(/<(script|style|noscript|svg|nav|header|footer|aside|form|iframe|figure|button)\b[\s\S]*?<\/\1>/gi, " ");
const main = h.match(/<article[\s>][\s\S]*<\/article>/i) || h.match(/<main[\s>][\s\S]*<\/main>/i);
if (main) h = main[0];
const blocks = (h.match(/<(p|h2|h3)\b[^>]*>[\s\S]*?<\/\1>/gi) || []).map(x => ({ tag: x.slice(1, 3).replace(/\W/g, "").toLowerCase(), text: toText(x) }));
const paras = blocks.filter(b => b.tag === "p" && b.text.length >= 60).map(b => b.text);
const heads = blocks.filter(b => b.tag !== "p" && b.text.length > 2 && b.text.length < 90).map(b => b.text);
const text = paras.join("\n\n");
return { desc, paras, heads, text, words: text ? text.split(/\s+/).length : 0 };
}
// ---------- Reader: the post's own text inside BlogPulse ----------
// Paragraphs, subheadings, lists, quotes and code in page order; menus, footers and sharing bars are dropped.
// ── Getting the page (app-blueprints · read-aloud 1.2.0, Step 9): snippets/read-aloud/page-fetch.scriptable.js, names kept ──
const plain = s => decode(stripTags(String(s || ""))); // the text of a bit of HTML or markdown (page-fetch expects plain())
// Scriptable's JavaScriptCore is not a browser: no URL, URLSearchParams, setTimeout or atob here.
// 2. Plain helpers (no URL class in Scriptable)
const absUrl = (href, base) => { // a link on a page, made absolute
if (!href) return base;
if (/^https?:\/\//i.test(href)) return href;
const origin = (String(base).match(/^https?:\/\/[^/]+/i) || [""])[0];
if (href.startsWith("//")) return "https:" + href;
if (href.startsWith("/")) return origin + href;
return String(base).replace(/[?#].*$/, "").replace(/[^/]*$/, "") + href;
};
const unq = v => String(v || "").replace(/&/g, "&").replace(/"/g, '"').replace(///gi, "/").replace(///g, "/");
const hostOfUrl = u => (String(u).match(/^https?:\/\/([^/?#]+)/i) || [])[1] || String(u);
function formFields(form) { // a form's inputs as { name: value }, single or double quotes
const out = {};
for (const inp of form.match(/<input[^>]+>/gi) || []) {
const name = (inp.match(/name=["']([^"']+)["']/i) || [])[1], val = unq((inp.match(/value=["']([^"']*)["']/i) || [])[1] || "");
if (name) out[name] = val;
}
return out;
}
const enc = o => Object.entries(o).map(([k, v]) => encodeURIComponent(k) + "=" + encodeURIComponent(v)).join("&");
function cookiesOf(resp, domainRx, jar) {
for (const c of (resp && resp.cookies) || []) if (c && c.name && domainRx.test(c.domain || "")) jar[c.name] = c.value;
return jar;
}
// 3. Consent walls in Europe. Answered once, the way a person would in Safari, and the cookies kept in settings,
// so later pages load directly. Yahoo: "Accept all" plus Yahoo's own copyConsent step. Google: its "Reject all" form.
let consentRun = null, consentAt = 0;
async function yahooConsent(html, pageUrl, log = []) {
const forms = html.match(/<form\b[\s\S]*?<\/form>/gi) || [];
const form = forms.find(f => /name=["']?agree/i.test(f)) || forms.find(f => /method=["']?post/i.test(f));
if (!form) { log.push(`Yahoo's consent page had no form to answer (${html.length} characters)`); return false; }
const action = absUrl(unq((form.match(/action=["']([^"']*)["']/i) || [])[1]), pageUrl);
const fields = formFields(form);
for (const k of Object.keys(fields)) if (/^(agree|reject)$/i.test(k)) delete fields[k];
const sessionId = fields.sessionId || (pageUrl.match(/[?&]sessionId=([^&#]+)/) || [])[1] || "";
if (!fields.consentUUID) fields.consentUUID = "default";
if (!fields.namespace) fields.namespace = "yahoo";
const jar = {}, r = new Request(action);
r.method = "POST"; r.timeoutInterval = cfg("fetchTimeout");
r.headers = { "User-Agent": cfg("userAgent"), "Content-Type": "application/x-www-form-urlencoded", "Referer": pageUrl };
r.body = enc(fields) + "&agree=agree&agree=agree";
await r.loadString();
cookiesOf(r.response, /yahoo/i, jar);
log.push(`Answered Yahoo's consent (HTTP ${r.response ? r.response.statusCode : "?"})`);
if (sessionId) { // Yahoo's page does this next: copy the consent to its other sites, which sets the cookies articles need
const g = new Request(`https://guce.yahoo.com/copyConsent?sessionId=${encodeURIComponent(sessionId)}`);
g.timeoutInterval = cfg("fetchTimeout"); g.headers = { "User-Agent": cfg("userAgent"), "Referer": action };
try { await g.loadString(); cookiesOf(g.response, /yahoo/i, jar); } catch (e) { log.push("Yahoo's copyConsent failed: " + (e.message || e)); }
}
const names = Object.keys(jar);
log.push(names.length ? `Yahoo returned cookies: ${names.join(", ")}` : "Yahoo returned no cookies");
startLog(`Yahoo consent answered: ${names.length ? names.join(", ") : "no cookies returned"}`);
if (names.length) { settings.yahooCookie = names.map(k => k + "=" + jar[k]).join("; "); write("settings", settings); consentAt = Date.now(); }
return true;
}
const googleCookie = () => settings.googleCookie || "SOCS=CAI";
async function googleConsent(html, pageUrl, log = []) {
const forms = (html.match(/<form\b[\s\S]*?<\/form>/gi) || []).filter(f => /consent\.google|\/save/i.test((f.match(/action=["']([^"']*)["']/i) || [])[1] || ""));
const form = forms.find(f => formFields(f).set_eom === "true") || forms[0]; // "Reject all"
if (!form) { log.push(`Google's consent page had no form to answer (${html.length} characters)`); return false; }
const r = new Request(absUrl(unq((form.match(/action=["']([^"']*)["']/i) || [])[1]), pageUrl));
r.method = "POST"; r.timeoutInterval = cfg("fetchTimeout");
r.headers = { "User-Agent": cfg("userAgent"), "Content-Type": "application/x-www-form-urlencoded", "Referer": pageUrl };
r.body = enc(formFields(form));
await r.loadString();
const jar = cookiesOf(r.response, /google/i, {}), names = Object.keys(jar);
log.push(`Answered Google's consent (HTTP ${r.response ? r.response.statusCode : "?"})${names.length ? ", cookies: " + names.join(", ") : ", no cookies returned"}`);
startLog(`Google consent answered: ${names.length ? names.join(", ") : "no cookies returned"}`);
if (names.length) { settings.googleCookie = names.map(k => k + "=" + jar[k]).join("; "); write("settings", settings); }
return true;
}
// 4. One page, with the cookies for its site, through any consent wall, logging each step.
// Google News links are followed to the publisher first (googleNewsURL); Google's own pages are never the article.
async function getPage(u) {
const r = new Request(u), host = hostOfUrl(u);
r.timeoutInterval = cfg("fetchTimeout");
r.headers = { "User-Agent": cfg("userAgent"), "Accept": "text/html,application/xhtml+xml;q=0.9,*/*;q=0.5", "Accept-Language": "en-US,en;q=0.8" };
if (settings.yahooCookie && /(^|\.)yahoo\.com$/i.test(host)) r.headers.Cookie = settings.yahooCookie;
if (/(^|\.)google\.[a-z.]+$/i.test(host)) r.headers.Cookie = googleCookie();
const html = await r.loadString();
return { html: html || "", url: (r.response && r.response.url) || u, code: r.response ? r.response.statusCode : 0 };
}
async function fetchPage(url, log = []) {
if (/news\.google\./i.test(url)) {
const real = await googleNewsURL(url, log).catch(e => { log.push("Google News link not decoded: " + String(e.message || e).slice(0, 60)); return null; });
if (real) { log.push("Google News link leads to " + hostOfUrl(real)); url = real; } else log.push("Google News didn't say where the article is");
}
let r = await getPage(url);
log.push(`Opened ${hostOfUrl(r.url)}: HTTP ${r.code}, ${r.html.length} characters`);
if (/consent\.yahoo\.com|guce\.yahoo\.com/i.test(r.url)) { // one answer at a time, shared by pages loading together
if (!consentRun && settings.yahooCookie && Date.now() - consentAt < 60e3) consentRun = Promise.resolve(true);
if (!consentRun) consentRun = yahooConsent(r.html, r.url, log).catch(e => { log.push("Yahoo consent failed: " + (e.message || e)); return false; }).then(ok => { consentRun = null; return ok; });
let ok = false;
try { ok = await consentRun; } catch (e) {}
if (ok) { r = await getPage(url); log.push(`Opened it again: ${hostOfUrl(r.url)}, HTTP ${r.code}, ${r.html.length} characters`); }
}
if (/consent\.google\./i.test(r.url) && await googleConsent(r.html, r.url, log).catch(() => false)) { r = await getPage(url); log.push(`Opened it again: ${hostOfUrl(r.url)}, HTTP ${r.code}`); }
if (/(consent|guce)\.[a-z.]*\//i.test(r.url)) log.push("Still a consent page");
if (r.code >= 400 || /(consent|guce)\.[a-z.]*\//i.test(r.url) || /news\.google\./i.test(r.url)) r.html = "";
return r;
}
// 5. Google News article links hide the publisher. Older ids carry it inside; newer ones are exchanged for it with the
// signature and timestamp on Google's article page (behind Google's consent wall in Europe).
async function googleNewsURL(url, log = []) {
const id = (String(url).match(/\/articles\/([^?/#]+)/) || [])[1];
if (!id) return null;
try {
const b = id.replace(/-/g, "+").replace(/_/g, "/"), raw = Data.fromBase64String(b + "===".slice((b.length + 3) % 4)).toRawString() || "";
const m = raw.match(/https?:\/\/[^\s"'<>\x00-\x1f\x7f-\uffff]+/);
if (m && !/^AU_yq/.test(raw.slice(4))) return m[0];
} catch (e) {}
let p = await getPage(`https://news.google.com/rss/articles/${id}`);
if (/consent\.google\./i.test(p.url) && await googleConsent(p.html, p.url, log).catch(() => false)) p = await getPage(`https://news.google.com/rss/articles/${id}`);
const sg = (p.html.match(/data-n-a-sg="([^"]+)"/) || [])[1], ts = (p.html.match(/data-n-a-ts="([^"]+)"/) || [])[1];
if (!sg || !ts) { log.push(/consent\.google\./i.test(p.url) ? "Google still shows its consent page" : "Google's article page had no link signature"); return null; }
const inner = `["garturlreq",[["X","X",["X","X"],null,null,1,1,"US:en",null,1,null,null,null,null,null,0,1],"X","X",1,[1,1,1],1,1,null,0,0,null,0],"${id}",${ts},"${sg}"]`;
const r = new Request("https://news.google.com/_/DotsSplashUi/data/batchexecute");
r.method = "POST"; r.timeoutInterval = cfg("fetchTimeout");
r.headers = { "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", "User-Agent": cfg("userAgent"), "Cookie": googleCookie() };
r.body = "f.req=" + encodeURIComponent(JSON.stringify([[["Fbv4je", inner, null, "generic"]]]));
const txt = await r.loadString();
for (const line of String(txt).split("\n")) {
if (!line.startsWith("[")) continue;
try { for (const row of JSON.parse(line)) if (row[0] === "wrb.fr" && row[2]) { const res = JSON.parse(row[2]); if (res[0] === "garturlres" && /^https?:/.test(res[1])) return res[1]; } } catch (e) {}
}
return null;
}
// 6. Jina Reader (r.jina.ai): pages that still won't open from the phone (a consent wall that can't be answered,
// pages built by scripts, apps blocked) are opened on Jina's servers, which send back markdown. Only the page's
// public address is sent. Never for Google News links (Jina refuses them with HTTP 403).
const proxyCache = {};
async function proxyRead(url, log = []) {
if (settings.readerProxy === false) { log.push("Jina Reader is off (Settings › Reading)"); return null; }
if (!/^https?:\/\//i.test(url)) return null;
if (/news\.google\.|consent\.google\./i.test(url)) { log.push("Jina Reader can't follow Google News links"); return null; }
if (proxyCache[url] !== undefined) { log.push(proxyCache[url] ? `Jina Reader (earlier): ${proxyCache[url].words} words` : "Jina Reader couldn't read it earlier"); return proxyCache[url]; }
try {
const r = new Request("https://r.jina.ai/" + url);
r.timeoutInterval = Math.max(20, cfg("fetchTimeout"));
r.headers = { "Accept": "text/plain", "X-Return-Format": "markdown", "User-Agent": cfg("userAgent") };
const jk = secretFor("jina");
if (jk) r.headers.Authorization = "Bearer " + jk;
const txt = await r.loadString(), code = r.response ? r.response.statusCode : 0;
if (code >= 400 || !txt) {
let why = String(txt || "").replace(/\s+/g, " ").trim();
try { const j = JSON.parse(txt); why = j.readableMessage || j.message || j.detail || why; } catch (e) {}
throw new Error(`HTTP ${code}${why ? ": " + why.slice(0, 120) : ""}${[401, 402, 403].includes(code) && !jk ? " (a free Jina Reader key may help)" : ""}`);
}
const md = (txt.split(/\nMarkdown Content:\s*\n/)[1] || txt).trim();
const clean = t => plain(t.replace(/!\[[^\]]*\]\([^)]*\)/g, " ").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[*_`]{1,3}([^*_`]+)[*_`]{1,3}/g, "$1")).replace(/\s+/g, " ").trim();
const links = t => (t.match(/\]\(/g) || []).length, blocks = [];
for (const raw of md.split(/\n\s*\n/)) for (const line0 of raw.split(/\n(?=\s*(?:[-*+]|\d+\.)\s)/)) {
const line = line0.trim(), t = clean(line.replace(/^#{1,6}\s+|^>\s?|^[-*+]\s+|^\d+\.\s+/gm, ""));
if (!t || /^(advertisement|story continues|view comments|recommended stories)/i.test(t)) continue;
if (links(line) >= 3 && links(line) * 40 > t.length) continue; // a row of links: navigation
if (/^#{1,6}\s/.test(line)) { if (t.length > 2 && t.length < 120) blocks.push({ t: "h", text: t }); }
else if (/^[-*+]\s|^\d+\.\s/.test(line)) { if (t.length >= 15) blocks.push({ t: "li", text: t }); }
else if (/^>/.test(line)) { if (t.length >= 20) blocks.push({ t: "q", text: t }); }
else if (t.length >= 30) blocks.push({ t: "p", text: t });
}
const words = blocks.filter(b => b.t !== "h").reduce((n, b) => n + b.text.split(/\s+/).length, 0);
log.push(`Jina Reader: HTTP ${code}, ${words} words${words < 80 ? " (too few)" : ""}`);