-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
415 lines (359 loc) · 11.7 KB
/
main.ts
File metadata and controls
415 lines (359 loc) · 11.7 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
import { AtpAgent, RichText } from "npm:@atproto/api";
import { type Record as AptRecord } from "npm:@atproto/api/dist/client/types/app/bsky/feed/post.js";
type AptEmbed = AptRecord["embed"];
const BLUESKY_HOST = Deno.env.get("BLUESKY_HOST") || "https://bsky.social";
const BLUESKY_USERNAME = Deno.env.get("BLUESKY_USERNAME");
const BLUESKY_PASSWORD = Deno.env.get("BLUESKY_PASSWORD");
/**
* For more information about the baseline status stages, see:
*
* https://web-platform-dx.github.io/web-features/
*/
type BaselineStatus = "newly" | "widely" | "limited";
type BrowserKey =
| "chrome"
| "chrome_android"
| "edge"
| "firefox"
| "firefox_android"
| "safari"
| "safari_ios";
type BrowserVersion = string;
type FeatureStatus = {
baseline: "high";
baseline_high_date: string;
baseline_low_date: string;
support: Record<BrowserKey, BrowserVersion>;
} | {
baseline: "low";
baseline_low_date: string;
support: Record<BrowserKey, BrowserVersion>;
} | {
baseline: false;
support: Record<BrowserKey, BrowserVersion>;
};
interface Feature {
compat_features: string[];
description: string;
description_html: string;
group: string;
name: string;
spec: string;
status: FeatureStatus;
discouraged?: {
according_to: string[];
alternatives?: string[];
};
}
interface FeatureWithId extends Feature {
feature_id: string;
baseline_stage: BaselineStatus;
}
const kv = await Deno.openKv();
async function publishNewlyAvailableFeaturesToBluesky(
features: FeatureWithId[],
) {
for (const feature of features) {
await publishFeatureToBluesky(feature);
}
}
async function publishFeatureToBluesky(feature: FeatureWithId) {
const { name, description, feature_id } = feature;
const webStatusUrl =
`https://web-platform-dx.github.io/web-features-explorer/features/${feature_id}`;
// Construct the message to be sent to Bluesky:
let preamble = "";
switch (feature.baseline_stage) {
case "widely":
preamble = `Widely available`;
break;
case "newly":
preamble = `Newly available`;
break;
case "limited":
preamble = `Limited`;
break;
default:
preamble = `Feature`;
}
const MAX_DESCRIPTION_LENGTH = 200;
const ELIPSIS = "…";
const sanitizedDescription =
description.length + ELIPSIS.length > MAX_DESCRIPTION_LENGTH
? description.slice(0, MAX_DESCRIPTION_LENGTH - ELIPSIS.length) + "..."
: description; // Limit description to 200 characters
const sanitizedName = name.slice(0, 80); // Limit name to 50 characters
const message = `${preamble}: ${sanitizedName}\n\n` +
`Description: ${sanitizedDescription}\n\n`;
// Get the Web Platform Features Explorer logo to use as a thumbnail
const WEBPLATFORM_LOGO_URL =
"https://web-platform-dx.github.io/web-features-explorer/assets/logo.png";
const thumbnailData = await fetch(WEBPLATFORM_LOGO_URL);
const thumbnailBlob = await thumbnailData.blob();
// Get the Bluesky agent
const agent = await getBlueskyAgent();
// Send the message to Bluesky:
await sendMessageToBluesky(
agent,
message,
webStatusUrl,
thumbnailBlob,
`${sanitizedName} on Webplatform Feature Explorer`,
sanitizedDescription,
);
}
async function sendMessageToBluesky(
agent: AtpAgent,
message: string,
embedUrl: string,
embedThumbnailData: Blob,
embedTitle: string,
embedDescription: string,
) {
// Upload and create the blob ref for the thumbnail
const thumbnailUploadResponse = await agent.uploadBlob(embedThumbnailData, {
encoding: "image/png",
});
if (!thumbnailUploadResponse.success) {
throw new Error(
`Failed to upload thumbnail to Bluesky: ${thumbnailUploadResponse}`,
);
}
const thumbnailBlobRef = thumbnailUploadResponse.data.blob;
const embed: AptEmbed = {
$type: "app.bsky.embed.external",
external: {
uri: embedUrl,
title: embedTitle,
description: embedDescription,
thumb: thumbnailBlobRef,
},
};
const rt = new RichText({ text: message });
await rt.detectFacets(agent);
const postRecord: AptRecord = {
$type: "app.bsky.feed.post",
text: rt.text,
facets: rt.facets,
embed,
createdAt: new Date().toISOString(),
};
await agent.post(postRecord);
}
async function getBlueskyAgent(): Promise<AtpAgent> {
if (!BLUESKY_USERNAME || !BLUESKY_PASSWORD || !BLUESKY_HOST) {
throw new Error("Missing Bluesky credentials");
}
const agent = new AtpAgent({
service: BLUESKY_HOST,
});
const sessionResponse = await agent.login({
identifier: BLUESKY_USERNAME,
password: BLUESKY_PASSWORD,
});
if (!sessionResponse.success) {
throw new Error(`Failed to login to Bluesky!`, { cause: sessionResponse });
}
return agent;
}
const WEB_PLATFORM_REPO = "web-platform-dx/web-features";
interface WebPlatformData {
features: Record<string, Feature>;
}
async function getLatestWebPlatformReleaseData(): Promise<WebPlatformData> {
// Use the GitHub API to get the latest release data
const response = await fetch(
`https://api.github.com/repos/${WEB_PLATFORM_REPO}/releases/latest`,
{
headers: {
"Accept": "application/vnd.github.v3+json",
"User-Agent": "web-features-bot",
},
},
);
if (!response.ok) {
throw new Error(
`Failed to fetch latest release data: ${response.statusText}`,
);
}
const releaseData = await response.json();
// Check the release assets for the url of the "data.json" file
const dataAsset = releaseData.assets.find((asset: { name?: string }) =>
asset.name === "data.json"
);
if (!dataAsset) {
throw new Error("No data.json asset found in the latest release");
}
const dataUrl = dataAsset.browser_download_url;
if (!dataUrl) {
throw new Error("No download URL found for data.json asset");
}
const dataResponse = await fetch(dataUrl);
if (!dataResponse.ok) {
throw new Error(`Failed to fetch data.json: ${dataResponse.statusText}`);
}
const latestData = await dataResponse.json();
return latestData;
}
async function hashFeature(feature: any): Promise<string> {
const featureString = JSON.stringify(feature);
const featureStringUtf8 = new TextEncoder().encode(featureString);
const hashBuffer = await crypto.subtle.digest("SHA-256", featureStringUtf8);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(
"",
);
return hashHex;
}
async function getFeatureHashFromDB(featureId: string): Promise<string | null> {
const existingHash = await kv.get<string>([`features`, featureId]);
if (existingHash) {
return existingHash.value;
}
return null;
}
async function setFeatureHashInDB(
featureId: string,
hash: string,
): Promise<void> {
await kv.set(["features", featureId], hash);
}
function featureBaselinStage(feature: Feature): BaselineStatus {
if (feature.status.baseline === "high") {
return "widely";
} else if (feature.status.baseline === "low") {
return "newly";
} else {
return "limited"; // Default to newly if baseline is false
}
}
async function extractNewFeaturesFromData(): Promise<FeatureWithId[]> {
// Retrieve the newest web-features data
const latestData = await getLatestWebPlatformReleaseData();
// For each item in the data, compare a hash of the item to one stored in the Deno.KV store
// If the hash is not found, publish the feature to Bluesky and store the hash in Deno.KV
const featureItems = latestData.features;
const newFeatureItems: FeatureWithId[] = [];
for (const featureKey of Object.keys(featureItems)) {
const item = featureItems[featureKey];
const featureHash = await hashFeature(item);
const existingHash = await getFeatureHashFromDB(featureKey);
if (existingHash === null || existingHash !== featureHash) {
const itemWithId: FeatureWithId = {
...item,
feature_id: featureKey,
baseline_stage: featureBaselinStage(item),
};
newFeatureItems.push(itemWithId);
await setFeatureHashInDB(featureKey, featureHash);
}
}
return newFeatureItems;
}
async function retrieveAndPostNewlyAvailableFeatures() {
const newFeatures = await extractNewFeaturesFromData();
await publishNewlyAvailableFeaturesToBluesky(newFeatures);
console.log(
`Published ${newFeatures.length} newly available features to Bluesky.`,
);
}
async function getDatabaseVersion() {
const version = await kv.get<number>(["db_version"]);
if (version && version.value !== null && typeof version.value === "number") {
return version.value;
}
return undefined; // Explicitly return undefined if no version is found
}
async function setDatabaseVersion(version: number) {
await kv.set(["db_version"], version);
}
const MIGRATIONS = [async () => {
// Populate the database with initial hashes of features
const latestData = await getLatestWebPlatformReleaseData();
const features = latestData.features;
console.log(
`Populating ${
Object.keys(features).length
} initial feature hashes in the database...`,
);
for (const featureKey of Object.keys(features)) {
const item = features[featureKey];
const featureHash = await hashFeature(item);
await setFeatureHashInDB(featureKey, featureHash);
}
console.log("Initial feature hashes populated in the database.");
}];
async function runMigrationsStartingFrom(startVersion: number) {
for (let i = startVersion; i < MIGRATIONS.length; i++) {
console.log(`Running migration ${i + 1}/${MIGRATIONS.length}...`);
await MIGRATIONS[i]();
console.log(`Migration ${i + 1} completed.`);
}
setDatabaseVersion(MIGRATIONS.length);
}
/**
* Delete all keys in the database, including the database version key.
* This is useful for resetting the database to a clean state.
*/
async function clearDatabase() {
// Retrieve all entries in the database, then delete them
const entries = kv.list({ prefix: [`features`] });
for await (const entry of entries) {
await kv.delete(entry.key);
}
// Also delete the database version key
await kv.delete(["db_version"]);
}
async function prepareDatabase() {
const currentVersion = await getDatabaseVersion();
if (currentVersion === undefined) {
await runMigrationsStartingFrom(0);
} else {
if (currentVersion < MIGRATIONS.length) {
await runMigrationsStartingFrom(currentVersion);
}
}
}
/**
* Used for testing purposes to clear a random feature from the database so that it will publish again to Bluesky.
*/
async function clearRandomFeatureFromDB(count: number = 1) {
const entries = kv.list({ prefix: [`features`] });
const keys = [];
for await (const entry of entries) {
keys.push(entry.key);
}
let deletedCount = 0;
const keysToDelete = keys.sort(() => Math.random() - 0.5).slice(0, count);
for (const key of keysToDelete) {
await kv.delete(key);
deletedCount++;
console.log(`Deleted feature hash: ${key.join("/")}`);
}
console.log(`Deleted ${deletedCount} feature hashes from the database.`);
}
async function entrypoint() {
await prepareDatabase();
await retrieveAndPostNewlyAvailableFeatures();
}
// Learn more at https://docs.deno.com/runtime/manual/examples/module_metadata#concepts
if (import.meta.main) {
// Retrieve the arguments passed to the script and if --clear-db is present, clear the database
const args = Deno.args;
if (args.includes("--clear-db")) {
console.log("Clearing the database...");
await clearDatabase();
console.log("Database cleared.");
Deno.exit(0);
}
if (args.includes("--clear-random-feature")) {
const countIndex = args.indexOf("--clear-random-feature");
const count = countIndex !== -1 && args[countIndex + 1]
? parseInt(args[countIndex + 1])
: 1;
await clearRandomFeatureFromDB(count);
Deno.exit(0);
}
await entrypoint();
}
export { entrypoint };