@getvitops/utils 7.0.0 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +131 -13
- package/dist/adc-BFrzpMHq.d.mts +25 -0
- package/dist/adc-BFrzpMHq.d.mts.map +1 -0
- package/dist/adc-D6aw2qgq.mjs +45 -0
- package/dist/adc-D6aw2qgq.mjs.map +1 -0
- package/dist/ads/index.d.mts +0 -1
- package/dist/ads/index.d.mts.map +1 -1
- package/dist/ads/index.mjs +4 -13
- package/dist/ads/index.mjs.map +1 -1
- package/dist/{cloudflare-CD8vwrgj.mjs → cloudflare-CgAsXiqe.mjs} +24 -2
- package/dist/cloudflare-CgAsXiqe.mjs.map +1 -0
- package/dist/color/index.d.mts +0 -3
- package/dist/color/index.d.mts.map +1 -1
- package/dist/color/index.mjs +0 -3
- package/dist/color/index.mjs.map +1 -1
- package/dist/index.d.mts +5 -190
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +5 -240
- package/dist/index.mjs.map +1 -1
- package/dist/indexing/index.d.mts +2 -24
- package/dist/indexing/index.d.mts.map +1 -1
- package/dist/indexing/index.mjs +7 -69
- package/dist/indexing/index.mjs.map +1 -1
- package/dist/json-store-30CFCbZZ.mjs +38 -0
- package/dist/json-store-30CFCbZZ.mjs.map +1 -0
- package/dist/media/index.d.mts +0 -2
- package/dist/media/index.d.mts.map +1 -1
- package/dist/media/index.mjs +4 -20
- package/dist/media/index.mjs.map +1 -1
- package/dist/notify/index.d.mts +1 -2
- package/dist/notify/index.d.mts.map +1 -1
- package/dist/onboarding/index.d.mts +1 -1
- package/dist/onboarding/index.d.mts.map +1 -1
- package/dist/onboarding/index.mjs +7 -17
- package/dist/onboarding/index.mjs.map +1 -1
- package/dist/reviews/index.d.mts +154 -0
- package/dist/reviews/index.d.mts.map +1 -0
- package/dist/reviews/index.mjs +218 -0
- package/dist/reviews/index.mjs.map +1 -0
- package/dist/schema/index.d.mts +191 -0
- package/dist/schema/index.d.mts.map +1 -0
- package/dist/schema/index.mjs +241 -0
- package/dist/schema/index.mjs.map +1 -0
- package/dist/security/index.d.mts +48 -0
- package/dist/security/index.d.mts.map +1 -0
- package/dist/security/index.mjs +80 -0
- package/dist/security/index.mjs.map +1 -0
- package/dist/{token-BlShEM6J.d.mts → token-Bz_-igw-.d.mts} +3 -2
- package/dist/{token-BlShEM6J.d.mts.map → token-Bz_-igw-.d.mts.map} +1 -1
- package/dist/{token-CuyjDo6I.mjs → token-DkKC5m23.mjs} +16 -3
- package/dist/{token-CuyjDo6I.mjs.map → token-DkKC5m23.mjs.map} +1 -1
- package/dist/tracking/index.d.mts +1 -1
- package/dist/{types-C3lHaSrU.d.mts → types-CHHjzRrv.d.mts} +1 -2
- package/dist/types-CHHjzRrv.d.mts.map +1 -0
- package/package.json +25 -2
- package/dist/cloudflare-CD8vwrgj.mjs.map +0 -1
- package/dist/types-C3lHaSrU.d.mts.map +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { a as SCOPES, c as googleHeaders, i as GoogleOAuth, n as GoogleAuthLike, o as ServiceAccount, r as GoogleCredential, s as googleAccessToken, t as GoogleAuth } from "../token-
|
|
1
|
+
import { a as SCOPES, c as googleHeaders, i as GoogleOAuth, n as GoogleAuthLike, o as ServiceAccount, r as GoogleCredential, s as googleAccessToken, t as GoogleAuth } from "../token-Bz_-igw-.mjs";
|
|
2
|
+
import { n as adcQuotaProject, r as parseAdcUser, t as adcCredentialsPath } from "../adc-BFrzpMHq.mjs";
|
|
2
3
|
|
|
3
4
|
//#region src/indexing/types.d.ts
|
|
4
5
|
/**
|
|
@@ -105,9 +106,7 @@ interface IndexingPlan {
|
|
|
105
106
|
}
|
|
106
107
|
interface PlanInput {
|
|
107
108
|
config: IndexingConfig;
|
|
108
|
-
/** The sitemap as it stands now. */
|
|
109
109
|
current: SitemapEntry[];
|
|
110
|
-
/** The previous run's state, if any. */
|
|
111
110
|
previous?: Snapshot | undefined;
|
|
112
111
|
/** `--urls`: submit exactly these, skipping the diff. */
|
|
113
112
|
explicitUrls?: string[] | undefined;
|
|
@@ -270,26 +269,5 @@ interface InspectionResult {
|
|
|
270
269
|
*/
|
|
271
270
|
declare function inspectUrl(auth: GoogleAuthLike, siteUrl: string, inspectionUrl: string, fetchImpl?: typeof fetch): Promise<InspectionResult>;
|
|
272
271
|
//#endregion
|
|
273
|
-
//#region src/google/adc.d.ts
|
|
274
|
-
/** A parsed ADC user credential, or `undefined` if `raw` is not one. */
|
|
275
|
-
declare function parseAdcUser(raw: string): GoogleOAuth | undefined;
|
|
276
|
-
/** The quota project gcloud recorded with an ADC credential, if any. */
|
|
277
|
-
declare function adcQuotaProject(raw: string): string | undefined;
|
|
278
|
-
/**
|
|
279
|
-
* Where gcloud keeps ADC when nothing points at it explicitly.
|
|
280
|
-
*
|
|
281
|
-
* Reading the well-known path is what makes "I'm logged in" mean something, instead
|
|
282
|
-
* of asking the user to export a variable at a file gcloud already wrote.
|
|
283
|
-
* `CLOUDSDK_CONFIG` wins if set, as it does for gcloud itself.
|
|
284
|
-
*
|
|
285
|
-
* Every input is a parameter so the platform branches are testable on one machine.
|
|
286
|
-
*/
|
|
287
|
-
declare function adcCredentialsPath(opts: {
|
|
288
|
-
env: Record<string, string | undefined>;
|
|
289
|
-
platform: string;
|
|
290
|
-
home: string | undefined;
|
|
291
|
-
join: (...parts: string[]) => string;
|
|
292
|
-
}): string | undefined;
|
|
293
|
-
//#endregion
|
|
294
272
|
export { type ChannelPlan, type GoogleAuth, type GoogleAuthLike, type GoogleCredential, type GoogleOAuth, INDEXNOW_BATCH, INDEXNOW_ENDPOINT, type IndexNowConfig, type IndexNowPlan, type IndexingConfig, type IndexingPlan, type InspectionResult, type ParsedSitemap, type PlanInput, SCOPES, SNAPSHOT_PATH, type SearchConsoleConfig, type SearchConsolePlan, type ServiceAccount, type SitemapEntry, type SitemapReader, type Snapshot, type SubmitResult, type UrlReason, adcCredentialsPath, adcQuotaProject, collectEntries, formatPlan, googleAccessToken, googleHeaders, inspectUrl, keyFileContents, newKey, parseAdcUser, parseServiceAccount, parseSitemap, plan, readSnapshot, resolveKeyLocation, resolveSitemapUrl, serviceAccountToken, submitBatch, submitSitemap, toSnapshot, verifyKeyFile, writeSnapshot };
|
|
295
273
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/indexing/types.ts","../../src/indexing/plan.ts","../../src/indexing/sitemap.ts","../../src/indexing/snapshot.ts","../../src/indexing/indexnow.ts","../../src/indexing/gsc.ts"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/indexing/types.ts","../../src/indexing/plan.ts","../../src/indexing/sitemap.ts","../../src/indexing/snapshot.ts","../../src/indexing/indexnow.ts","../../src/indexing/gsc.ts"],"mappings":";;;;;;;;AAoBA;;;;;;UAAiB,cAAA;EASP;AAAA;AAIV;;EARE,GAAA;EAUA;EARA,WAAA;EAce;EAZf,QAAA;AAAA;;UAIe,mBAAA;EAYf;EAVA,OAAA;EAWW;EATX,eAAe;AAAA;;UAIA,cAAA;EAaT;EAXN,SAAA;EAee;EAbf,UAAA;EACA,QAAA,GAAW,cAAA;EACX,aAAA,GAAgB,mBAAmB;EAa5B;EAXP,YAAA;EAeuB;;;;EAVvB,MAAA;AAAA;;UAIe,YAAA;EACf,GAAA;EACA,OAAO;AAAA;;UAIQ,QAAA;EACf,OAAA;EACA,UAAA;EACA,OAAA;ECpD4B;EDsD5B,OAAA,EAAS,MAAM;AAAA;;;cCtDJ,iBAAA;;;ADsBI;AAIjB;;cCnBa,cAAA;;KAGD,SAAA;;UAGK,WAAA;EACf,OAAA;EDkBA;EChBA,IAAI;AAAA;AAAA,UAGW,YAAA,SAAqB,WAAW;EAC/C,QAAA;EACA,WAAA;EACA,GAAA;EACA,IAAA;;EAEA,OAAA;AAAA;AAAA,UAGe,iBAAA,SAA0B,WAAW;EACpD,OAAO;A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AAAA;AJEQ;AAIV;;;;AAIiB;AAIjB;;AAZU,iBIiCY,aAAA,CACpB,WAAA,UACA,GAAA,UACA,SAAA,UAAkB,KAAA,GACjB,OAAO;EAAG,EAAA;EAAa,MAAA;AAAA;;;;;iBAqBJ,WAAA,CACpB,IAAA,EAAM,YAAA,EACN,IAAA,YACA,SAAA,UAAkB,KAAA,GACjB,OAAA,CAAQ,YAAA;;;;;;;;;;;iBCpDK,mBAAA,CAAoB,GAAA,WAAc,cAAc;;ALexD;AAIR;;;iBKFgB,mBAAA,CACd,OAAA,EAAS,cAAA,EACT,SAAA,UAAkB,KAAA,EAClB,GAAA,YACC,OAAA;ALAM;AAIT;;;;;;AAJS,iBKea,aAAA,CACpB,IAAA,EAAM,cAAA,EACN,OAAA,UACA,UAAA,UACA,SAAA,UAAkB,KAAA,GACjB,OAAA;EAAU,EAAA;EAAa,MAAA;EAAgB,OAAA;AAAA;;UAgBzB,gBAAA;EACf,GAAA;EJlFW;EIoFX,OAAA;;EAEA,aAAA;EACA,aAAA;EJhFW;EIkFX,OAAA;EACA,KAAA;AAAA;AJnFyB;AAG3B;;;;AAH2B,iBI2FL,UAAA,CACpB,IAAA,EAAM,cAAA,EACN,OAAA,UACA,aAAA,UACA,SAAA,UAAkB,KAAA,GACjB,OAAA,CAAQ,gBAAA"}
|
package/dist/indexing/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { n as writeVersioned, t as readVersioned } from "../json-store-30CFCbZZ.mjs";
|
|
2
|
+
import { a as googleHeaders, i as googleAccessToken, n as encodeSite, r as errorDetail, t as SCOPES } from "../token-DkKC5m23.mjs";
|
|
3
|
+
import { n as adcQuotaProject, r as parseAdcUser, t as adcCredentialsPath } from "../adc-D6aw2qgq.mjs";
|
|
4
4
|
import { randomBytes } from "node:crypto";
|
|
5
5
|
|
|
6
6
|
//#region src/indexing/plan.ts
|
|
@@ -269,16 +269,6 @@ async function collectEntries(source, read) {
|
|
|
269
269
|
|
|
270
270
|
//#endregion
|
|
271
271
|
//#region src/indexing/snapshot.ts
|
|
272
|
-
/**
|
|
273
|
-
* The previous run's sitemap state — what makes "only submit what changed"
|
|
274
|
-
* possible at all.
|
|
275
|
-
*
|
|
276
|
-
* A plain JSON file rather than anything cleverer, because the thing reading it is
|
|
277
|
-
* usually a CI job restoring a cache directory. It must survive being absent
|
|
278
|
-
* (first run, cold cache) without pretending nothing changed — `readSnapshot`
|
|
279
|
-
* returns `undefined` there and `plan()` treats that as "submit everything, and
|
|
280
|
-
* say so".
|
|
281
|
-
*/
|
|
282
272
|
/** Default location, relative to the consumer's project root. */
|
|
283
273
|
const SNAPSHOT_PATH = ".vitops/sitemap-snapshot.json";
|
|
284
274
|
/**
|
|
@@ -290,14 +280,7 @@ const SNAPSHOT_PATH = ".vitops/sitemap-snapshot.json";
|
|
|
290
280
|
* failure this whole command exists to remove.
|
|
291
281
|
*/
|
|
292
282
|
function readSnapshot(path) {
|
|
293
|
-
|
|
294
|
-
try {
|
|
295
|
-
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
296
|
-
if (raw?.version !== 1 || typeof raw.entries !== "object" || raw.entries === null) return void 0;
|
|
297
|
-
return raw;
|
|
298
|
-
} catch {
|
|
299
|
-
return;
|
|
300
|
-
}
|
|
283
|
+
return readVersioned(path, "entries");
|
|
301
284
|
}
|
|
302
285
|
/** Build a snapshot from the entries just read. */
|
|
303
286
|
function toSnapshot(sitemapUrl, entries, takenAt) {
|
|
@@ -319,8 +302,7 @@ function toSnapshot(sitemapUrl, entries, takenAt) {
|
|
|
319
302
|
* silently drop a page from every future run.
|
|
320
303
|
*/
|
|
321
304
|
function writeSnapshot(path, snapshot) {
|
|
322
|
-
|
|
323
|
-
writeFileSync(path, `${JSON.stringify(snapshot, null, 2)}\n`);
|
|
305
|
+
writeVersioned(path, snapshot);
|
|
324
306
|
}
|
|
325
307
|
|
|
326
308
|
//#endregion
|
|
@@ -467,7 +449,6 @@ function serviceAccountToken(account, fetchImpl = fetch, now = Date.now()) {
|
|
|
467
449
|
scope: SCOPES.webmasters
|
|
468
450
|
}, fetchImpl, now);
|
|
469
451
|
}
|
|
470
|
-
const encodeSite = (siteUrl) => encodeURIComponent(siteUrl);
|
|
471
452
|
/**
|
|
472
453
|
* Re-submit a sitemap — the automated form of the manual resubmit in the UI.
|
|
473
454
|
*
|
|
@@ -484,11 +465,11 @@ async function submitSitemap(auth, siteUrl, sitemapUrl, fetchImpl = fetch) {
|
|
|
484
465
|
ok: true,
|
|
485
466
|
status: res.status
|
|
486
467
|
};
|
|
487
|
-
const
|
|
468
|
+
const message = await errorDetail(res, (status) => status === 403 ? `403 — check that siteUrl "${siteUrl}" matches the Search Console property exactly and that the service account is an owner of it` : void 0);
|
|
488
469
|
return {
|
|
489
470
|
ok: false,
|
|
490
471
|
status: res.status,
|
|
491
|
-
message
|
|
472
|
+
message
|
|
492
473
|
};
|
|
493
474
|
}
|
|
494
475
|
/**
|
|
@@ -520,49 +501,6 @@ async function inspectUrl(auth, siteUrl, inspectionUrl, fetchImpl = fetch) {
|
|
|
520
501
|
};
|
|
521
502
|
}
|
|
522
503
|
|
|
523
|
-
//#endregion
|
|
524
|
-
//#region src/google/adc.ts
|
|
525
|
-
/** A parsed ADC user credential, or `undefined` if `raw` is not one. */
|
|
526
|
-
function parseAdcUser(raw) {
|
|
527
|
-
let parsed;
|
|
528
|
-
try {
|
|
529
|
-
parsed = JSON.parse(raw);
|
|
530
|
-
} catch {
|
|
531
|
-
return;
|
|
532
|
-
}
|
|
533
|
-
if (parsed.type !== "authorized_user") return void 0;
|
|
534
|
-
if (!parsed.client_id || !parsed.client_secret || !parsed.refresh_token) return void 0;
|
|
535
|
-
return {
|
|
536
|
-
clientId: parsed.client_id,
|
|
537
|
-
clientSecret: parsed.client_secret,
|
|
538
|
-
refreshToken: parsed.refresh_token
|
|
539
|
-
};
|
|
540
|
-
}
|
|
541
|
-
/** The quota project gcloud recorded with an ADC credential, if any. */
|
|
542
|
-
function adcQuotaProject(raw) {
|
|
543
|
-
try {
|
|
544
|
-
return JSON.parse(raw).quota_project_id || void 0;
|
|
545
|
-
} catch {
|
|
546
|
-
return;
|
|
547
|
-
}
|
|
548
|
-
}
|
|
549
|
-
/**
|
|
550
|
-
* Where gcloud keeps ADC when nothing points at it explicitly.
|
|
551
|
-
*
|
|
552
|
-
* Reading the well-known path is what makes "I'm logged in" mean something, instead
|
|
553
|
-
* of asking the user to export a variable at a file gcloud already wrote.
|
|
554
|
-
* `CLOUDSDK_CONFIG` wins if set, as it does for gcloud itself.
|
|
555
|
-
*
|
|
556
|
-
* Every input is a parameter so the platform branches are testable on one machine.
|
|
557
|
-
*/
|
|
558
|
-
function adcCredentialsPath(opts) {
|
|
559
|
-
const { env, platform, home, join } = opts;
|
|
560
|
-
const sdk = env.CLOUDSDK_CONFIG;
|
|
561
|
-
if (sdk) return join(sdk, "application_default_credentials.json");
|
|
562
|
-
if (platform === "win32") return env.APPDATA ? join(env.APPDATA, "gcloud", "application_default_credentials.json") : void 0;
|
|
563
|
-
return home ? join(home, ".config", "gcloud", "application_default_credentials.json") : void 0;
|
|
564
|
-
}
|
|
565
|
-
|
|
566
504
|
//#endregion
|
|
567
505
|
export { INDEXNOW_BATCH, INDEXNOW_ENDPOINT, SCOPES, SNAPSHOT_PATH, adcCredentialsPath, adcQuotaProject, collectEntries, formatPlan, googleAccessToken, googleHeaders, inspectUrl, keyFileContents, newKey, parseAdcUser, parseServiceAccount, parseSitemap, plan, readSnapshot, resolveKeyLocation, resolveSitemapUrl, serviceAccountToken, submitBatch, submitSitemap, toSnapshot, verifyKeyFile, writeSnapshot };
|
|
568
506
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/indexing/plan.ts","../../src/indexing/sitemap.ts","../../src/indexing/snapshot.ts","../../src/indexing/indexnow.ts","../../src/indexing/gsc.ts","../../src/google/adc.ts"],"sourcesContent":["/**\n * Every decision `vitops search notify` makes, as one pure function.\n *\n * Pure in the load-bearing sense: no `fetch`, no `fs`, no clock. Everything the\n * command could get wrong — submitting a staging URL, submitting nothing because a\n * cache was cold, submitting a URL IndexNow will reject for the wrong host — is\n * decided here and asserted in `plan.test.ts`. The I/O modules beside this one do\n * what they are told and nothing else.\n *\n * That split is the same one `@getvitops/core`'s consent store makes against its\n * DOM wiring, for the same reason: the consequential logic has to be testable\n * without the environment it runs in.\n */\nimport type { IndexingConfig, SitemapEntry, Snapshot } from './types.ts';\n\nexport const INDEXNOW_ENDPOINT = 'https://api.indexnow.org/indexnow';\n\n/**\n * IndexNow's own cap per submission. Batches larger than this are split rather\n * than truncated — a silently dropped tail is the failure mode this command is\n * meant to eliminate, not reproduce.\n */\nexport const INDEXNOW_BATCH = 10_000;\n\n/** Why the URL set is what it is. */\nexport type UrlReason = 'explicit' | 'all' | 'cold' | 'diff';\n\n/** A channel's decision: on, or off with a stated reason. */\nexport interface ChannelPlan {\n enabled: boolean;\n /** Why it's off. Present iff `enabled` is false. */\n skip?: string;\n}\n\nexport interface IndexNowPlan extends ChannelPlan {\n endpoint: string;\n keyLocation?: string | undefined;\n key?: string | undefined;\n host?: string | undefined;\n /** URL batches, each within `INDEXNOW_BATCH`. */\n batches: string[][];\n}\n\nexport interface SearchConsolePlan extends ChannelPlan {\n siteUrl?: string | undefined;\n}\n\nexport interface IndexingPlan {\n /** Set when the whole run is refused. Nothing is submitted. */\n blocked?: string;\n /** Always computed; `undefined` when nothing in the config resolves to one. */\n sitemapUrl: string | undefined;\n /** URLs that changed and should be submitted. */\n urls: string[];\n reason: UrlReason;\n /** No usable previous snapshot — `urls` is everything. */\n cold: boolean;\n indexNow: IndexNowPlan;\n searchConsole: SearchConsolePlan;\n /** URLs `--check` will inspect. */\n check: string[];\n /** Things the operator needs to read. Printed by `--dry` and by a real run. */\n notes: string[];\n}\n\nexport interface PlanInput {\n config: IndexingConfig;\n /** The sitemap as it stands now. */\n current: SitemapEntry[];\n /** The previous run's state, if any. */\n previous?: Snapshot | undefined;\n /** `--urls`: submit exactly these, skipping the diff. */\n explicitUrls?: string[] | undefined;\n /** `--all`: submit every URL in the sitemap. */\n all?: boolean | undefined;\n}\n\nconst trimSlash = (s: string) => s.replace(/\\/+$/, '');\n\nfunction hostOf(url: string): string | undefined {\n try {\n return new URL(url).host;\n } catch {\n return undefined;\n }\n}\n\nfunction chunk<T>(items: T[], size: number): T[][] {\n if (items.length === 0) return [];\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\n return out;\n}\n\n/**\n * Resolve the sitemap URL.\n *\n * `sitemap-index.xml` is @astrojs/sitemap's default filename and is what\n * `vitops({ sitemap })` registers, so it is the right default here. It resolves to\n * a flat `<urlset>` on a small site, which `parseSitemap` handles by reading the\n * root element rather than the name.\n */\nexport function resolveSitemapUrl(config: IndexingConfig): string | undefined {\n if (config.sitemapUrl) return config.sitemapUrl;\n if (!config.canonical) return undefined;\n return `${trimSlash(config.canonical)}/sitemap-index.xml`;\n}\n\n/** Resolve the IndexNow key file URL. */\nexport function resolveKeyLocation(config: IndexingConfig): string | undefined {\n const indexNow = config.indexNow;\n if (!indexNow) return undefined;\n if (indexNow.keyLocation) return indexNow.keyLocation;\n if (!config.canonical) return undefined;\n return `${trimSlash(config.canonical)}/${indexNow.key}.txt`;\n}\n\n/** Which URLs differ from the snapshot. */\nfunction diff(current: SitemapEntry[], previous: Snapshot): string[] {\n const changed: string[] = [];\n for (const e of current) {\n const before = previous.entries[e.loc];\n // Absent from the snapshot → new. Present with a different lastmod → updated.\n // A removed URL is deliberately not reported: there is nothing to submit for a\n // page that no longer exists, and IndexNow has no deletion semantics.\n if (before === undefined || before !== (e.lastmod ?? '')) changed.push(e.loc);\n }\n return changed;\n}\n\n/**\n * Decide what this run should do.\n *\n * Ordering of the URL-selection rules matters and is not arbitrary: an explicit\n * `--urls` is an operator overriding the tool, `--all` is an operator overriding\n * the diff, a cold snapshot is the tool having no basis to narrow, and the diff is\n * the normal path. Each is reported in `reason` so `--dry` explains itself.\n */\nexport function plan(input: PlanInput): IndexingPlan {\n const { config, current, previous, explicitUrls, all } = input;\n const notes: string[] = [];\n\n const sitemapUrl = resolveSitemapUrl(config);\n const check = config.priorityUrls ?? [];\n\n /*\n * The robots gate, before anything else.\n *\n * `environments.<env>.robots` already states whether a deployment is meant to be\n * indexed. Submitting a `noindex` environment's URLs to IndexNow is not a\n * no-op that the directive later undoes — it publishes the staging host to\n * several search engines and their AI crawlers, and asks them to come look. The\n * config knows the answer, so the tool must not need to be told twice.\n */\n if (config.robots && /\\bnoindex\\b/i.test(config.robots)) {\n return {\n blocked: `environment robots policy is \"${config.robots}\" — refusing to ask search engines to index an environment marked noindex`,\n sitemapUrl,\n urls: [],\n reason: 'diff',\n cold: false,\n indexNow: { enabled: false, skip: 'blocked', endpoint: INDEXNOW_ENDPOINT, batches: [] },\n searchConsole: { enabled: false, skip: 'blocked' },\n check: [],\n notes,\n };\n }\n\n const cold = !explicitUrls && !all && !previous;\n\n let urls: string[];\n let reason: UrlReason;\n if (explicitUrls?.length) {\n urls = explicitUrls;\n reason = 'explicit';\n } else if (all) {\n urls = current.map((e) => e.loc);\n reason = 'all';\n } else if (!previous) {\n urls = current.map((e) => e.loc);\n reason = 'cold';\n notes.push(\n `no previous snapshot — treating all ${urls.length} URLs as changed. Persist ${'`.vitops/`'} between runs (a CI cache) so later runs submit only what moved.`,\n );\n } else {\n urls = diff(current, previous);\n reason = 'diff';\n }\n\n /*\n * The foreign-sitemap check.\n *\n * A 404 fails loudly; a sitemap that is well-formed and *someone else's* does\n * not. A downstream site's sitemap route collided with its CMS's, so the URL\n * returned 200 with a valid document listing pages that were not theirs, and\n * the run reported a healthy cold submission. Nothing downstream can catch\n * this — the URLs parse, the diff works, the submission succeeds.\n *\n * Compared against the resolved environment origin rather than the canonical,\n * for the same reason `toIndexingConfig` derives the origin that way: on a\n * staging run the canonical IS the foreign host.\n */\n if (config.canonical && urls.length) {\n const own = hostOf(`${trimSlash(config.canonical)}/`);\n const foreign = [...new Set(urls.map(hostOf).filter((h): h is string => !!h && h !== own))];\n if (foreign.length)\n notes.push(\n `sitemap contains ${urls.length - urls.filter((u) => hostOf(u) === own).length} URL(s) on ` +\n `${foreign.join(', ')} rather than ${own} — check that ${sitemapUrl} is this site's own ` +\n `sitemap and not another route answering that path.`,\n );\n }\n\n /*\n * The lastmod warning.\n *\n * Without per-URL lastmod the diff can still see pages appear and disappear, but\n * it cannot see one change — so an edited page is never resubmitted and the\n * command quietly does less than it appears to. Worth a note every run, because\n * the output otherwise looks identical to the healthy case.\n */\n if (reason === 'diff' || reason === 'cold') {\n const withLastmod = current.filter((e) => e.lastmod).length;\n if (current.length > 0 && withLastmod === 0)\n notes.push(\n 'no <lastmod> in the sitemap — only added/removed pages can be detected, never an edit. Wire `gitLastmod()` into your sitemap options, or pass --all.',\n );\n else if (withLastmod < current.length)\n notes.push(\n `${current.length - withLastmod} of ${current.length} sitemap entries have no <lastmod> — edits to those pages cannot be detected.`,\n );\n }\n\n // ── IndexNow ────────────────────────────────────────────────────────────────\n const keyLocation = resolveKeyLocation(config);\n const keyHost = keyLocation ? hostOf(keyLocation) : undefined;\n let indexNow: IndexNowPlan;\n if (!config.indexNow) {\n indexNow = {\n enabled: false,\n skip: 'not configured (seo.indexing.indexNow)',\n endpoint: INDEXNOW_ENDPOINT,\n batches: [],\n };\n } else if (!keyLocation) {\n indexNow = {\n enabled: false,\n skip: 'no keyLocation and no domains.canonical to derive one',\n endpoint: config.indexNow.endpoint ?? INDEXNOW_ENDPOINT,\n key: config.indexNow.key,\n batches: [],\n };\n } else {\n /*\n * IndexNow requires every URL in a submission to share the key file's host.\n * A mixed batch is rejected whole, so the off-host URLs are dropped here and\n * named — silently sending them would fail the on-host ones too.\n */\n const onHost = urls.filter((u) => hostOf(u) === keyHost);\n const offHost = urls.length - onHost.length;\n if (offHost > 0)\n notes.push(\n `IndexNow: dropped ${offHost} URL(s) not on ${keyHost} — a submission must match its key file's host.`,\n );\n indexNow = {\n enabled: onHost.length > 0,\n ...(onHost.length === 0 ? { skip: 'no URLs to submit' } : {}),\n endpoint: config.indexNow.endpoint ?? INDEXNOW_ENDPOINT,\n keyLocation,\n key: config.indexNow.key,\n ...(keyHost ? { host: keyHost } : {}),\n batches: chunk(onHost, INDEXNOW_BATCH),\n };\n }\n\n // ── Search Console ──────────────────────────────────────────────────────────\n // Independent of `urls`: resubmitting the sitemap is what tells Google to\n // re-read it, and it is worth doing whenever the sitemap was rebuilt — there is\n // no per-URL submission to gate on, because Google exposes none.\n let searchConsole: SearchConsolePlan;\n if (!config.searchConsole) {\n searchConsole = { enabled: false, skip: 'not configured (seo.indexing.searchConsole)' };\n } else if (config.searchConsole.resubmitSitemap === false) {\n searchConsole = {\n enabled: false,\n skip: 'resubmitSitemap is false',\n siteUrl: config.searchConsole.siteUrl,\n };\n } else if (!sitemapUrl) {\n searchConsole = {\n enabled: false,\n skip: 'no sitemapUrl and no domains.canonical to derive one',\n siteUrl: config.searchConsole.siteUrl,\n };\n } else {\n searchConsole = { enabled: true, siteUrl: config.searchConsole.siteUrl };\n }\n\n return {\n sitemapUrl,\n urls,\n reason,\n cold,\n indexNow,\n searchConsole,\n check,\n notes,\n };\n}\n\n/** Render a plan as the human-readable block `--dry` prints. */\nexport function formatPlan(p: IndexingPlan): string {\n const lines: string[] = [];\n if (p.blocked) {\n lines.push(`✗ blocked — ${p.blocked}`);\n return lines.join('\\n');\n }\n lines.push(`sitemap ${p.sitemapUrl ?? '(none)'}`);\n lines.push(`urls ${p.urls.length} (${p.reason})`);\n\n lines.push(\n p.indexNow.enabled\n ? `IndexNow ${p.indexNow.batches.reduce((n, b) => n + b.length, 0)} URL(s) → ${p.indexNow.endpoint}`\n : `IndexNow skipped — ${p.indexNow.skip}`,\n );\n lines.push(\n p.searchConsole.enabled\n ? `Search Console resubmit sitemap → ${p.searchConsole.siteUrl}`\n : `Search Console skipped — ${p.searchConsole.skip}`,\n );\n for (const n of p.notes) lines.push(` ! ${n}`);\n return lines.join('\\n');\n}\n","/**\n * Sitemap parsing — enough of it, and no more.\n *\n * Hand-rolled rather than pulled from an XML library. A sitemap is a closed,\n * trivially-shaped document (`<urlset>` of `<url>`, or `<sitemapindex>` of\n * `<sitemap>`, each carrying `<loc>` and optionally `<lastmod>`), and this package\n * installs into every consumer project — a parser dependency for two element names\n * is not a trade worth making. The same reasoning the legal renderer applies to its\n * markdown subset: exactly as capable as the documents it has to read.\n */\nimport type { SitemapEntry } from './types.ts';\n\n/** What a sitemap document turned out to be. */\nexport interface ParsedSitemap {\n /** `<url>` entries, when this was a `<urlset>`. */\n entries: SitemapEntry[];\n /** Child sitemap URLs, when this was a `<sitemapindex>`. */\n sitemaps: string[];\n}\n\n/**\n * The five predefined XML entities, plus numeric character references.\n *\n * Not cosmetic: a sitemap URL carrying a query string is written `?a=1&b=2`,\n * and submitting the un-decoded form means submitting a URL the site does not\n * serve — which IndexNow accepts and then silently fails to crawl.\n */\nfunction decodeXml(s: string): string {\n return (\n s\n .replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(Number.parseInt(h, 16)))\n .replace(/&#(\\d+);/g, (_, d) => String.fromCodePoint(Number.parseInt(d, 10)))\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n // `&` last: decoding it first would let `&lt;` collapse to `<`.\n .replace(/&/g, '&')\n );\n}\n\nconst tag = (block: string, name: string): string | undefined => {\n const m = new RegExp(`<${name}(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</${name}>`, 'i').exec(block);\n return m ? decodeXml(m[1]!.trim()) : undefined;\n};\n\nfunction blocks(xml: string, name: string): string[] {\n const out: string[] = [];\n const re = new RegExp(`<${name}(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</${name}>`, 'gi');\n let m: RegExpExecArray | null;\n while ((m = re.exec(xml))) out.push(m[1]!);\n return out;\n}\n\n/**\n * Parse a sitemap or sitemap index.\n *\n * Which one it is comes from the root element, not from the filename — an\n * `sitemap-index.xml` that is actually a flat `<urlset>` is common enough\n * (@astrojs/sitemap emits an index only past `entryLimit`) that keying on the name\n * would misread the single-file case as \"no URLs\".\n */\nexport function parseSitemap(xml: string): ParsedSitemap {\n if (/<sitemapindex[\\s>]/i.test(xml))\n return {\n entries: [],\n sitemaps: blocks(xml, 'sitemap')\n .map((b) => tag(b, 'loc'))\n .filter((l): l is string => !!l),\n };\n\n const entries: SitemapEntry[] = [];\n for (const b of blocks(xml, 'url')) {\n const loc = tag(b, 'loc');\n if (!loc) continue; // `<loc>` is required; an entry without one is unusable\n const lastmod = tag(b, 'lastmod');\n entries.push(lastmod ? { loc, lastmod } : { loc });\n }\n return { entries, sitemaps: [] };\n}\n\n/** Reads a sitemap from a URL or a local path. */\nexport type SitemapReader = (source: string) => Promise<string>;\n\n/**\n * Resolve a sitemap to its full entry list, following an index one level down.\n *\n * One level is the whole spec — the sitemaps protocol forbids an index pointing at\n * another index — so recursing further would only chase a malformed document.\n * Child fetches run sequentially: a large site's index can list dozens of files,\n * and hammering the consumer's own origin to save a second is a poor trade.\n */\nexport async function collectEntries(\n source: string,\n read: SitemapReader,\n): Promise<{ entries: SitemapEntry[]; sources: string[] }> {\n const root = parseSitemap(await read(source));\n if (root.sitemaps.length === 0) return { entries: root.entries, sources: [source] };\n\n const entries: SitemapEntry[] = [];\n const sources: string[] = [];\n for (const child of root.sitemaps) {\n const parsed = parseSitemap(await read(child));\n entries.push(...parsed.entries);\n sources.push(child);\n }\n return { entries, sources };\n}\n","/**\n * The previous run's sitemap state — what makes \"only submit what changed\"\n * possible at all.\n *\n * A plain JSON file rather than anything cleverer, because the thing reading it is\n * usually a CI job restoring a cache directory. It must survive being absent\n * (first run, cold cache) without pretending nothing changed — `readSnapshot`\n * returns `undefined` there and `plan()` treats that as \"submit everything, and\n * say so\".\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\nimport type { SitemapEntry, Snapshot } from './types.ts';\n\n/** Default location, relative to the consumer's project root. */\nexport const SNAPSHOT_PATH = '.vitops/sitemap-snapshot.json';\n\n/**\n * Read a snapshot, or `undefined` when there isn't a usable one.\n *\n * A corrupt or wrong-version file reads as absent, not as empty. The distinction\n * matters: \"absent\" submits everything, whereas an empty entry map would look like\n * a site that legitimately has no URLs and submit nothing — the silent-success\n * failure this whole command exists to remove.\n */\nexport function readSnapshot(path: string): Snapshot | undefined {\n if (!existsSync(path)) return undefined;\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as Snapshot;\n if (raw?.version !== 1 || typeof raw.entries !== 'object' || raw.entries === null)\n return undefined;\n return raw;\n } catch {\n return undefined;\n }\n}\n\n/** Build a snapshot from the entries just read. */\nexport function toSnapshot(sitemapUrl: string, entries: SitemapEntry[], takenAt: string): Snapshot {\n const map: Record<string, string> = {};\n for (const e of entries) map[e.loc] = e.lastmod ?? '';\n return { version: 1, sitemapUrl, takenAt, entries: map };\n}\n\n/**\n * Write the snapshot, creating its directory.\n *\n * Call this only after a submission actually succeeded. Writing it eagerly would\n * record URLs as notified that never were, and because the next run diffs against\n * it, those URLs would never be submitted again — a single transient 503 would\n * silently drop a page from every future run.\n */\nexport function writeSnapshot(path: string, snapshot: Snapshot): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(snapshot, null, 2)}\\n`);\n}\n","/**\n * IndexNow submission.\n *\n * Honoured by Bing, Yandex, Naver, Seznam and Yep — and, through Bing's index, by\n * the AI crawlers built on it. **Not** by Google, which has never adopted the\n * protocol despite testing it; nothing here should be described to a consumer as\n * affecting Google results.\n *\n * Participating engines share submissions with each other, so one endpoint is\n * normally the whole integration.\n */\nimport { randomBytes } from 'node:crypto';\nimport type { IndexNowPlan } from './plan.ts';\n\n/** Generate a key. 32 hex characters, the conventional shape. */\nexport function newKey(): string {\n return randomBytes(16).toString('hex');\n}\n\n/** The body of the key file served at `keyLocation`: the key, and nothing else. */\nexport const keyFileContents = (key: string): string => `${key}\\n`;\n\nexport interface SubmitResult {\n ok: boolean;\n status: number;\n urls: number;\n /** The endpoint's own explanation, when it gave one. */\n message?: string;\n}\n\n/**\n * How the endpoint's status codes actually read.\n *\n * `403` and `422` are the two that matter and they are easy to misdiagnose: both\n * mean the key file is wrong, not that the URLs are.\n */\nfunction explain(status: number): string | undefined {\n switch (status) {\n case 200:\n case 202:\n return undefined;\n case 400:\n return 'bad request — malformed URL list';\n case 403:\n return 'key file not found or its contents do not match the key';\n case 422:\n return 'a submitted URL does not belong to the key file host, or the key does not match';\n case 429:\n return 'rate limited — too many submissions';\n default:\n return `unexpected status ${status}`;\n }\n}\n\n/**\n * Verify the key file is live and correct before submitting.\n *\n * Worth a request of its own because of how IndexNow fails: a submission with an\n * unreachable key file returns `403`, but one with a *reachable* key file whose\n * contents are stale is accepted with `202` and then silently discarded. Checking\n * first is the only way to tell \"submitted\" from \"submitted and ignored\".\n */\nexport async function verifyKeyFile(\n keyLocation: string,\n key: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; reason?: string }> {\n let res: Response;\n try {\n res = await fetchImpl(keyLocation, { method: 'GET' });\n } catch (e) {\n return { ok: false, reason: `could not fetch ${keyLocation}: ${(e as Error).message}` };\n }\n if (!res.ok) return { ok: false, reason: `${keyLocation} returned ${res.status}` };\n const body = (await res.text()).trim();\n if (body !== key)\n return {\n ok: false,\n reason: `${keyLocation} does not contain the configured key (found ${body.length} chars)`,\n };\n return { ok: true };\n}\n\n/**\n * Submit one batch. Callers iterate `plan.batches` — the split is the planner's\n * job, so that what gets sent is decided in the pure layer and visible in `--dry`.\n */\nexport async function submitBatch(\n plan: IndexNowPlan,\n urls: string[],\n fetchImpl: typeof fetch = fetch,\n): Promise<SubmitResult> {\n const body = {\n host: plan.host,\n key: plan.key,\n keyLocation: plan.keyLocation,\n urlList: urls,\n };\n const res = await fetchImpl(plan.endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json; charset=utf-8' },\n body: JSON.stringify(body),\n });\n const message = explain(res.status);\n return { ok: res.ok, status: res.status, urls: urls.length, ...(message ? { message } : {}) };\n}\n","/**\n * Google Search Console — the two things its API will actually do.\n *\n * Worth stating plainly, because the gap between what people expect and what\n * exists is the whole reason this module is small: **there is no \"request\n * indexing\" endpoint.** The button in the Search Console UI is not exposed in the\n * API or anywhere else, and the sitemap ping endpoint was removed in 2023. What\n * remains is `sitemaps.submit` (write) and `urlInspection` (read).\n *\n * The Indexing API is deliberately not wired here. It is scoped to `JobPosting`\n * and `BroadcastEvent`; it accepts other URLs and discards them, and using it for\n * general pages violates its terms with the consumer's own GCP project on the\n * line. A toolchain should not ship that as a documented path.\n *\n * Auth is minted by hand rather than through `googleapis`, which would be an\n * enormous dependency in a CLI that installs into every consumer project, for two\n * endpoints. The exchange itself lives in `../google/token.ts` — it is shared with\n * the onboarding module, which needs the same token from a different grant.\n */\nimport {\n googleAccessToken,\n googleHeaders,\n SCOPES,\n type GoogleAuthLike,\n type ServiceAccount,\n} from '../google/token.ts';\n\nexport type { ServiceAccount } from '../google/token.ts';\n\n/**\n * Parse a service-account credential from its two supported sources.\n *\n * `VITOPS_GSC_SERVICE_ACCOUNT` holds the JSON inline (what a CI secret store\n * gives you); `GOOGLE_APPLICATION_CREDENTIALS` holds a path (Google's own\n * convention, and what a local `gcloud` setup already has). Supporting both means\n * neither environment has to be reshaped to fit the tool.\n */\nexport function parseServiceAccount(raw: string): ServiceAccount {\n let parsed: Partial<ServiceAccount>;\n try {\n parsed = JSON.parse(raw) as Partial<ServiceAccount>;\n } catch {\n throw new Error('service account is not valid JSON');\n }\n if (!parsed.client_email || !parsed.private_key)\n throw new Error('service account JSON is missing client_email or private_key');\n return { client_email: parsed.client_email, private_key: parsed.private_key };\n}\n\n/**\n * Exchange a service-account key for an access token (RS256 JWT bearer flow).\n *\n * `now` is a parameter so this is testable without mocking the clock.\n */\nexport function serviceAccountToken(\n account: ServiceAccount,\n fetchImpl: typeof fetch = fetch,\n now: number = Date.now(),\n): Promise<string> {\n return googleAccessToken(\n { kind: 'service-account', account, scope: SCOPES.webmasters },\n fetchImpl,\n now,\n );\n}\n\nconst encodeSite = (siteUrl: string) => encodeURIComponent(siteUrl);\n\n/**\n * Re-submit a sitemap — the automated form of the manual resubmit in the UI.\n *\n * A `403` here almost always means `siteUrl` doesn't match the property exactly\n * (`sc-domain:acme.ca` vs `https://acme.ca/`) or the service account isn't an\n * owner of it, rather than that the sitemap is bad.\n */\nexport async function submitSitemap(\n auth: GoogleAuthLike,\n siteUrl: string,\n sitemapUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; message?: string }> {\n const url = `https://www.googleapis.com/webmasters/v3/sites/${encodeSite(siteUrl)}/sitemaps/${encodeURIComponent(sitemapUrl)}`;\n const res = await fetchImpl(url, {\n method: 'PUT',\n headers: googleHeaders(auth),\n });\n if (res.ok) return { ok: true, status: res.status };\n const detail =\n res.status === 403\n ? `403 — check that siteUrl \"${siteUrl}\" matches the Search Console property exactly and that the service account is an owner of it`\n : `${res.status}: ${await res.text()}`;\n return { ok: false, status: res.status, message: detail };\n}\n\n/** What the URL Inspection API said about one page. */\nexport interface InspectionResult {\n url: string;\n /** Google's verdict, e.g. `PASS`, `NEUTRAL`, `FAIL`. */\n verdict?: string;\n /** e.g. `INDEXING_ALLOWED`, `BLOCKED_BY_ROBOTS_TXT`. */\n coverageState?: string;\n lastCrawlTime?: string;\n /** True when Google reports the page as indexed. */\n indexed: boolean;\n error?: string;\n}\n\n/**\n * Inspect one URL. **Read-only** — this reports what Google did, it cannot ask for\n * anything. Quota is 2000 queries/day per property, which is why the caller works\n * from an explicit `priorityUrls` list rather than the whole sitemap.\n */\nexport async function inspectUrl(\n auth: GoogleAuthLike,\n siteUrl: string,\n inspectionUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<InspectionResult> {\n const res = await fetchImpl(\n 'https://searchconsole.googleapis.com/v1/urlInspection/index:inspect',\n {\n method: 'POST',\n headers: googleHeaders(auth, { 'content-type': 'application/json' }),\n body: JSON.stringify({ inspectionUrl, siteUrl }),\n },\n );\n if (!res.ok)\n return { url: inspectionUrl, indexed: false, error: `${res.status}: ${await res.text()}` };\n\n const body = (await res.json()) as {\n inspectionResult?: {\n indexStatusResult?: { verdict?: string; coverageState?: string; lastCrawlTime?: string };\n };\n };\n const r = body.inspectionResult?.indexStatusResult ?? {};\n return {\n url: inspectionUrl,\n ...(r.verdict ? { verdict: r.verdict } : {}),\n ...(r.coverageState ? { coverageState: r.coverageState } : {}),\n ...(r.lastCrawlTime ? { lastCrawlTime: r.lastCrawlTime } : {}),\n // `PASS` is the only verdict that means indexed. `NEUTRAL` covers \"discovered,\n // not indexed\" and \"excluded by canonical\" — both are *not indexed*, and\n // reading them as success would make --check pass on the exact pages it exists\n // to catch.\n indexed: r.verdict === 'PASS',\n };\n}\n","/**\n * Application Default Credentials — recognising a credential gcloud already wrote.\n *\n * `gcloud auth application-default login` writes\n * `{ client_id, client_secret, refresh_token, type: \"authorized_user\" }`, which maps\n * field-for-field onto the refresh-token grant this package already performs. So the\n * only thing that ever stood between \"I'm logged in to gcloud\" and `vitops search`\n * was recognising the shape.\n *\n * Pure, and here rather than in the CLI, for the reason the consent store and the\n * indexing planner are: the decidable part (is this a user credential? where would\n * gcloud have put it?) is worth asserting without a filesystem, and the CLI keeps\n * only the `readFileSync`. `type` is the discriminator Google's own libraries switch\n * on — never the presence of fields, since a service-account JSON also has a `type`.\n */\nimport type { GoogleOAuth } from './token.ts';\n\n/** A parsed ADC user credential, or `undefined` if `raw` is not one. */\nexport function parseAdcUser(raw: string): GoogleOAuth | undefined {\n let parsed: {\n type?: string;\n client_id?: string;\n client_secret?: string;\n refresh_token?: string;\n };\n try {\n parsed = JSON.parse(raw) as typeof parsed;\n } catch {\n return undefined;\n }\n if (parsed.type !== 'authorized_user') return undefined;\n // A truncated or half-written file is not a credential. Returning a partial one\n // would defer the failure to a token exchange whose error names the wrong cause.\n if (!parsed.client_id || !parsed.client_secret || !parsed.refresh_token) return undefined;\n return {\n clientId: parsed.client_id,\n clientSecret: parsed.client_secret,\n refreshToken: parsed.refresh_token,\n };\n}\n\n/** The quota project gcloud recorded with an ADC credential, if any. */\nexport function adcQuotaProject(raw: string): string | undefined {\n try {\n return (JSON.parse(raw) as { quota_project_id?: string }).quota_project_id || undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Where gcloud keeps ADC when nothing points at it explicitly.\n *\n * Reading the well-known path is what makes \"I'm logged in\" mean something, instead\n * of asking the user to export a variable at a file gcloud already wrote.\n * `CLOUDSDK_CONFIG` wins if set, as it does for gcloud itself.\n *\n * Every input is a parameter so the platform branches are testable on one machine.\n */\nexport function adcCredentialsPath(opts: {\n env: Record<string, string | undefined>;\n platform: string;\n home: string | undefined;\n join: (...parts: string[]) => string;\n}): string | undefined {\n const { env, platform, home, join } = opts;\n const sdk = env.CLOUDSDK_CONFIG;\n if (sdk) return join(sdk, 'application_default_credentials.json');\n if (platform === 'win32') {\n return env.APPDATA\n ? join(env.APPDATA, 'gcloud', 'application_default_credentials.json')\n : undefined;\n }\n return home ? join(home, '.config', 'gcloud', 'application_default_credentials.json') : undefined;\n}\n"],"mappings":";;;;;;AAeA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,iBAAiB;AAuD9B,MAAM,aAAa,MAAc,EAAE,QAAQ,QAAQ,EAAE;AAErD,SAAS,OAAO,KAAiC;CAC/C,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN;CACF;AACF;AAEA,SAAS,MAAS,OAAY,MAAqB;CACjD,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC;CAChC,MAAM,MAAa,CAAC;CACpB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAM,IAAI,KAAK,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC;CAC9E,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/indexing/plan.ts","../../src/indexing/sitemap.ts","../../src/indexing/snapshot.ts","../../src/indexing/indexnow.ts","../../src/indexing/gsc.ts"],"sourcesContent":["/**\n * Every decision `vitops search notify` makes, as one pure function.\n *\n * Pure in the load-bearing sense: no `fetch`, no `fs`, no clock. Everything the\n * command could get wrong — submitting a staging URL, submitting nothing because a\n * cache was cold, submitting a URL IndexNow will reject for the wrong host — is\n * decided here and asserted in `plan.test.ts`. The I/O modules beside this one do\n * what they are told and nothing else.\n *\n * That split is the same one `@getvitops/core`'s consent store makes against its\n * DOM wiring, for the same reason: the consequential logic has to be testable\n * without the environment it runs in.\n */\nimport type { IndexingConfig, SitemapEntry, Snapshot } from './types.ts';\n\nexport const INDEXNOW_ENDPOINT = 'https://api.indexnow.org/indexnow';\n\n/**\n * IndexNow's own cap per submission. Batches larger than this are split rather\n * than truncated — a silently dropped tail is the failure mode this command is\n * meant to eliminate, not reproduce.\n */\nexport const INDEXNOW_BATCH = 10_000;\n\n/** Why the URL set is what it is. */\nexport type UrlReason = 'explicit' | 'all' | 'cold' | 'diff';\n\n/** A channel's decision: on, or off with a stated reason. */\nexport interface ChannelPlan {\n enabled: boolean;\n /** Why it's off. Present iff `enabled` is false. */\n skip?: string;\n}\n\nexport interface IndexNowPlan extends ChannelPlan {\n endpoint: string;\n keyLocation?: string | undefined;\n key?: string | undefined;\n host?: string | undefined;\n /** URL batches, each within `INDEXNOW_BATCH`. */\n batches: string[][];\n}\n\nexport interface SearchConsolePlan extends ChannelPlan {\n siteUrl?: string | undefined;\n}\n\nexport interface IndexingPlan {\n /** Set when the whole run is refused. Nothing is submitted. */\n blocked?: string;\n /** Always computed; `undefined` when nothing in the config resolves to one. */\n sitemapUrl: string | undefined;\n /** URLs that changed and should be submitted. */\n urls: string[];\n reason: UrlReason;\n /** No usable previous snapshot — `urls` is everything. */\n cold: boolean;\n indexNow: IndexNowPlan;\n searchConsole: SearchConsolePlan;\n /** URLs `--check` will inspect. */\n check: string[];\n /** Things the operator needs to read. Printed by `--dry` and by a real run. */\n notes: string[];\n}\n\nexport interface PlanInput {\n config: IndexingConfig;\n current: SitemapEntry[];\n previous?: Snapshot | undefined;\n /** `--urls`: submit exactly these, skipping the diff. */\n explicitUrls?: string[] | undefined;\n /** `--all`: submit every URL in the sitemap. */\n all?: boolean | undefined;\n}\n\nconst trimSlash = (s: string) => s.replace(/\\/+$/, '');\n\nfunction hostOf(url: string): string | undefined {\n try {\n return new URL(url).host;\n } catch {\n return undefined;\n }\n}\n\nfunction chunk<T>(items: T[], size: number): T[][] {\n if (items.length === 0) return [];\n const out: T[][] = [];\n for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));\n return out;\n}\n\n/**\n * Resolve the sitemap URL.\n *\n * `sitemap-index.xml` is @astrojs/sitemap's default filename and is what\n * `vitops({ sitemap })` registers, so it is the right default here. It resolves to\n * a flat `<urlset>` on a small site, which `parseSitemap` handles by reading the\n * root element rather than the name.\n */\nexport function resolveSitemapUrl(config: IndexingConfig): string | undefined {\n if (config.sitemapUrl) return config.sitemapUrl;\n if (!config.canonical) return undefined;\n return `${trimSlash(config.canonical)}/sitemap-index.xml`;\n}\n\n/** Resolve the IndexNow key file URL. */\nexport function resolveKeyLocation(config: IndexingConfig): string | undefined {\n const indexNow = config.indexNow;\n if (!indexNow) return undefined;\n if (indexNow.keyLocation) return indexNow.keyLocation;\n if (!config.canonical) return undefined;\n return `${trimSlash(config.canonical)}/${indexNow.key}.txt`;\n}\n\n/** Which URLs differ from the snapshot. */\nfunction diff(current: SitemapEntry[], previous: Snapshot): string[] {\n const changed: string[] = [];\n for (const e of current) {\n const before = previous.entries[e.loc];\n // Absent from the snapshot → new. Present with a different lastmod → updated.\n // A removed URL is deliberately not reported: there is nothing to submit for a\n // page that no longer exists, and IndexNow has no deletion semantics.\n if (before === undefined || before !== (e.lastmod ?? '')) changed.push(e.loc);\n }\n return changed;\n}\n\n/**\n * Decide what this run should do.\n *\n * Ordering of the URL-selection rules matters and is not arbitrary: an explicit\n * `--urls` is an operator overriding the tool, `--all` is an operator overriding\n * the diff, a cold snapshot is the tool having no basis to narrow, and the diff is\n * the normal path. Each is reported in `reason` so `--dry` explains itself.\n */\nexport function plan(input: PlanInput): IndexingPlan {\n const { config, current, previous, explicitUrls, all } = input;\n const notes: string[] = [];\n\n const sitemapUrl = resolveSitemapUrl(config);\n const check = config.priorityUrls ?? [];\n\n /*\n * The robots gate, before anything else.\n *\n * `environments.<env>.robots` already states whether a deployment is meant to be\n * indexed. Submitting a `noindex` environment's URLs to IndexNow is not a\n * no-op that the directive later undoes — it publishes the staging host to\n * several search engines and their AI crawlers, and asks them to come look. The\n * config knows the answer, so the tool must not need to be told twice.\n */\n if (config.robots && /\\bnoindex\\b/i.test(config.robots)) {\n return {\n blocked: `environment robots policy is \"${config.robots}\" — refusing to ask search engines to index an environment marked noindex`,\n sitemapUrl,\n urls: [],\n reason: 'diff',\n cold: false,\n indexNow: { enabled: false, skip: 'blocked', endpoint: INDEXNOW_ENDPOINT, batches: [] },\n searchConsole: { enabled: false, skip: 'blocked' },\n check: [],\n notes,\n };\n }\n\n const cold = !explicitUrls && !all && !previous;\n\n let urls: string[];\n let reason: UrlReason;\n if (explicitUrls?.length) {\n urls = explicitUrls;\n reason = 'explicit';\n } else if (all) {\n urls = current.map((e) => e.loc);\n reason = 'all';\n } else if (!previous) {\n urls = current.map((e) => e.loc);\n reason = 'cold';\n notes.push(\n `no previous snapshot — treating all ${urls.length} URLs as changed. Persist ${'`.vitops/`'} between runs (a CI cache) so later runs submit only what moved.`,\n );\n } else {\n urls = diff(current, previous);\n reason = 'diff';\n }\n\n /*\n * The foreign-sitemap check.\n *\n * A 404 fails loudly; a sitemap that is well-formed and *someone else's* does\n * not. A downstream site's sitemap route collided with its CMS's, so the URL\n * returned 200 with a valid document listing pages that were not theirs, and\n * the run reported a healthy cold submission. Nothing downstream can catch\n * this — the URLs parse, the diff works, the submission succeeds.\n *\n * Compared against the resolved environment origin rather than the canonical,\n * for the same reason `toIndexingConfig` derives the origin that way: on a\n * staging run the canonical IS the foreign host.\n */\n if (config.canonical && urls.length) {\n const own = hostOf(`${trimSlash(config.canonical)}/`);\n const foreign = [...new Set(urls.map(hostOf).filter((h): h is string => !!h && h !== own))];\n if (foreign.length)\n notes.push(\n `sitemap contains ${urls.length - urls.filter((u) => hostOf(u) === own).length} URL(s) on ` +\n `${foreign.join(', ')} rather than ${own} — check that ${sitemapUrl} is this site's own ` +\n `sitemap and not another route answering that path.`,\n );\n }\n\n /*\n * The lastmod warning.\n *\n * Without per-URL lastmod the diff can still see pages appear and disappear, but\n * it cannot see one change — so an edited page is never resubmitted and the\n * command quietly does less than it appears to. Worth a note every run, because\n * the output otherwise looks identical to the healthy case.\n */\n if (reason === 'diff' || reason === 'cold') {\n const withLastmod = current.filter((e) => e.lastmod).length;\n if (current.length > 0 && withLastmod === 0)\n notes.push(\n 'no <lastmod> in the sitemap — only added/removed pages can be detected, never an edit. Wire `gitLastmod()` into your sitemap options, or pass --all.',\n );\n else if (withLastmod < current.length)\n notes.push(\n `${current.length - withLastmod} of ${current.length} sitemap entries have no <lastmod> — edits to those pages cannot be detected.`,\n );\n }\n\n // ── IndexNow ────────────────────────────────────────────────────────────────\n const keyLocation = resolveKeyLocation(config);\n const keyHost = keyLocation ? hostOf(keyLocation) : undefined;\n let indexNow: IndexNowPlan;\n if (!config.indexNow) {\n indexNow = {\n enabled: false,\n skip: 'not configured (seo.indexing.indexNow)',\n endpoint: INDEXNOW_ENDPOINT,\n batches: [],\n };\n } else if (!keyLocation) {\n indexNow = {\n enabled: false,\n skip: 'no keyLocation and no domains.canonical to derive one',\n endpoint: config.indexNow.endpoint ?? INDEXNOW_ENDPOINT,\n key: config.indexNow.key,\n batches: [],\n };\n } else {\n /*\n * IndexNow requires every URL in a submission to share the key file's host.\n * A mixed batch is rejected whole, so the off-host URLs are dropped here and\n * named — silently sending them would fail the on-host ones too.\n */\n const onHost = urls.filter((u) => hostOf(u) === keyHost);\n const offHost = urls.length - onHost.length;\n if (offHost > 0)\n notes.push(\n `IndexNow: dropped ${offHost} URL(s) not on ${keyHost} — a submission must match its key file's host.`,\n );\n indexNow = {\n enabled: onHost.length > 0,\n ...(onHost.length === 0 ? { skip: 'no URLs to submit' } : {}),\n endpoint: config.indexNow.endpoint ?? INDEXNOW_ENDPOINT,\n keyLocation,\n key: config.indexNow.key,\n ...(keyHost ? { host: keyHost } : {}),\n batches: chunk(onHost, INDEXNOW_BATCH),\n };\n }\n\n // ── Search Console ──────────────────────────────────────────────────────────\n // Independent of `urls`: resubmitting the sitemap is what tells Google to\n // re-read it, and it is worth doing whenever the sitemap was rebuilt — there is\n // no per-URL submission to gate on, because Google exposes none.\n let searchConsole: SearchConsolePlan;\n if (!config.searchConsole) {\n searchConsole = { enabled: false, skip: 'not configured (seo.indexing.searchConsole)' };\n } else if (config.searchConsole.resubmitSitemap === false) {\n searchConsole = {\n enabled: false,\n skip: 'resubmitSitemap is false',\n siteUrl: config.searchConsole.siteUrl,\n };\n } else if (!sitemapUrl) {\n searchConsole = {\n enabled: false,\n skip: 'no sitemapUrl and no domains.canonical to derive one',\n siteUrl: config.searchConsole.siteUrl,\n };\n } else {\n searchConsole = { enabled: true, siteUrl: config.searchConsole.siteUrl };\n }\n\n return {\n sitemapUrl,\n urls,\n reason,\n cold,\n indexNow,\n searchConsole,\n check,\n notes,\n };\n}\n\n/** Render a plan as the human-readable block `--dry` prints. */\nexport function formatPlan(p: IndexingPlan): string {\n const lines: string[] = [];\n if (p.blocked) {\n lines.push(`✗ blocked — ${p.blocked}`);\n return lines.join('\\n');\n }\n lines.push(`sitemap ${p.sitemapUrl ?? '(none)'}`);\n lines.push(`urls ${p.urls.length} (${p.reason})`);\n\n lines.push(\n p.indexNow.enabled\n ? `IndexNow ${p.indexNow.batches.reduce((n, b) => n + b.length, 0)} URL(s) → ${p.indexNow.endpoint}`\n : `IndexNow skipped — ${p.indexNow.skip}`,\n );\n lines.push(\n p.searchConsole.enabled\n ? `Search Console resubmit sitemap → ${p.searchConsole.siteUrl}`\n : `Search Console skipped — ${p.searchConsole.skip}`,\n );\n for (const n of p.notes) lines.push(` ! ${n}`);\n return lines.join('\\n');\n}\n","/**\n * Sitemap parsing — enough of it, and no more.\n *\n * Hand-rolled rather than pulled from an XML library. A sitemap is a closed,\n * trivially-shaped document (`<urlset>` of `<url>`, or `<sitemapindex>` of\n * `<sitemap>`, each carrying `<loc>` and optionally `<lastmod>`), and this package\n * installs into every consumer project — a parser dependency for two element names\n * is not a trade worth making. The same reasoning the legal renderer applies to its\n * markdown subset: exactly as capable as the documents it has to read.\n */\nimport type { SitemapEntry } from './types.ts';\n\n/** What a sitemap document turned out to be. */\nexport interface ParsedSitemap {\n /** `<url>` entries, when this was a `<urlset>`. */\n entries: SitemapEntry[];\n /** Child sitemap URLs, when this was a `<sitemapindex>`. */\n sitemaps: string[];\n}\n\n/**\n * The five predefined XML entities, plus numeric character references.\n *\n * Not cosmetic: a sitemap URL carrying a query string is written `?a=1&b=2`,\n * and submitting the un-decoded form means submitting a URL the site does not\n * serve — which IndexNow accepts and then silently fails to crawl.\n */\nfunction decodeXml(s: string): string {\n return (\n s\n .replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCodePoint(Number.parseInt(h, 16)))\n .replace(/&#(\\d+);/g, (_, d) => String.fromCodePoint(Number.parseInt(d, 10)))\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/"/g, '\"')\n .replace(/'/g, \"'\")\n // `&` last: decoding it first would let `&lt;` collapse to `<`.\n .replace(/&/g, '&')\n );\n}\n\nconst tag = (block: string, name: string): string | undefined => {\n const m = new RegExp(`<${name}(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</${name}>`, 'i').exec(block);\n return m ? decodeXml(m[1]!.trim()) : undefined;\n};\n\nfunction blocks(xml: string, name: string): string[] {\n const out: string[] = [];\n const re = new RegExp(`<${name}(?:\\\\s[^>]*)?>([\\\\s\\\\S]*?)</${name}>`, 'gi');\n let m: RegExpExecArray | null;\n while ((m = re.exec(xml))) out.push(m[1]!);\n return out;\n}\n\n/**\n * Parse a sitemap or sitemap index.\n *\n * Which one it is comes from the root element, not from the filename — an\n * `sitemap-index.xml` that is actually a flat `<urlset>` is common enough\n * (@astrojs/sitemap emits an index only past `entryLimit`) that keying on the name\n * would misread the single-file case as \"no URLs\".\n */\nexport function parseSitemap(xml: string): ParsedSitemap {\n if (/<sitemapindex[\\s>]/i.test(xml))\n return {\n entries: [],\n sitemaps: blocks(xml, 'sitemap')\n .map((b) => tag(b, 'loc'))\n .filter((l): l is string => !!l),\n };\n\n const entries: SitemapEntry[] = [];\n for (const b of blocks(xml, 'url')) {\n const loc = tag(b, 'loc');\n if (!loc) continue; // `<loc>` is required; an entry without one is unusable\n const lastmod = tag(b, 'lastmod');\n entries.push(lastmod ? { loc, lastmod } : { loc });\n }\n return { entries, sitemaps: [] };\n}\n\n/** Reads a sitemap from a URL or a local path. */\nexport type SitemapReader = (source: string) => Promise<string>;\n\n/**\n * Resolve a sitemap to its full entry list, following an index one level down.\n *\n * One level is the whole spec — the sitemaps protocol forbids an index pointing at\n * another index — so recursing further would only chase a malformed document.\n * Child fetches run sequentially: a large site's index can list dozens of files,\n * and hammering the consumer's own origin to save a second is a poor trade.\n */\nexport async function collectEntries(\n source: string,\n read: SitemapReader,\n): Promise<{ entries: SitemapEntry[]; sources: string[] }> {\n const root = parseSitemap(await read(source));\n if (root.sitemaps.length === 0) return { entries: root.entries, sources: [source] };\n\n const entries: SitemapEntry[] = [];\n const sources: string[] = [];\n for (const child of root.sitemaps) {\n const parsed = parseSitemap(await read(child));\n entries.push(...parsed.entries);\n sources.push(child);\n }\n return { entries, sources };\n}\n","/**\n * The previous run's sitemap state — what makes \"only submit what changed\"\n * possible at all.\n *\n * A plain JSON file rather than anything cleverer, because the thing reading it is\n * usually a CI job restoring a cache directory. It must survive being absent\n * (first run, cold cache) without pretending nothing changed — `readSnapshot`\n * returns `undefined` there and `plan()` treats that as \"submit everything, and\n * say so\".\n */\nimport type { SitemapEntry, Snapshot } from './types.ts';\nimport { readVersioned, writeVersioned } from '../json-store.ts';\n\n/** Default location, relative to the consumer's project root. */\nexport const SNAPSHOT_PATH = '.vitops/sitemap-snapshot.json';\n\n/**\n * Read a snapshot, or `undefined` when there isn't a usable one.\n *\n * A corrupt or wrong-version file reads as absent, not as empty. The distinction\n * matters: \"absent\" submits everything, whereas an empty entry map would look like\n * a site that legitimately has no URLs and submit nothing — the silent-success\n * failure this whole command exists to remove.\n */\nexport function readSnapshot(path: string): Snapshot | undefined {\n return readVersioned<Snapshot, 'entries'>(path, 'entries');\n}\n\n/** Build a snapshot from the entries just read. */\nexport function toSnapshot(sitemapUrl: string, entries: SitemapEntry[], takenAt: string): Snapshot {\n const map: Record<string, string> = {};\n for (const e of entries) map[e.loc] = e.lastmod ?? '';\n return { version: 1, sitemapUrl, takenAt, entries: map };\n}\n\n/**\n * Write the snapshot, creating its directory.\n *\n * Call this only after a submission actually succeeded. Writing it eagerly would\n * record URLs as notified that never were, and because the next run diffs against\n * it, those URLs would never be submitted again — a single transient 503 would\n * silently drop a page from every future run.\n */\nexport function writeSnapshot(path: string, snapshot: Snapshot): void {\n writeVersioned(path, snapshot);\n}\n","/**\n * IndexNow submission.\n *\n * Honoured by Bing, Yandex, Naver, Seznam and Yep — and, through Bing's index, by\n * the AI crawlers built on it. **Not** by Google, which has never adopted the\n * protocol despite testing it; nothing here should be described to a consumer as\n * affecting Google results.\n *\n * Participating engines share submissions with each other, so one endpoint is\n * normally the whole integration.\n */\nimport { randomBytes } from 'node:crypto';\nimport type { IndexNowPlan } from './plan.ts';\n\n/** Generate a key. 32 hex characters, the conventional shape. */\nexport function newKey(): string {\n return randomBytes(16).toString('hex');\n}\n\n/** The body of the key file served at `keyLocation`: the key, and nothing else. */\nexport const keyFileContents = (key: string): string => `${key}\\n`;\n\nexport interface SubmitResult {\n ok: boolean;\n status: number;\n urls: number;\n /** The endpoint's own explanation, when it gave one. */\n message?: string;\n}\n\n/**\n * How the endpoint's status codes actually read.\n *\n * `403` and `422` are the two that matter and they are easy to misdiagnose: both\n * mean the key file is wrong, not that the URLs are.\n */\nfunction explain(status: number): string | undefined {\n switch (status) {\n case 200:\n case 202:\n return undefined;\n case 400:\n return 'bad request — malformed URL list';\n case 403:\n return 'key file not found or its contents do not match the key';\n case 422:\n return 'a submitted URL does not belong to the key file host, or the key does not match';\n case 429:\n return 'rate limited — too many submissions';\n default:\n return `unexpected status ${status}`;\n }\n}\n\n/**\n * Verify the key file is live and correct before submitting.\n *\n * Worth a request of its own because of how IndexNow fails: a submission with an\n * unreachable key file returns `403`, but one with a *reachable* key file whose\n * contents are stale is accepted with `202` and then silently discarded. Checking\n * first is the only way to tell \"submitted\" from \"submitted and ignored\".\n */\nexport async function verifyKeyFile(\n keyLocation: string,\n key: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; reason?: string }> {\n let res: Response;\n try {\n res = await fetchImpl(keyLocation, { method: 'GET' });\n } catch (e) {\n return { ok: false, reason: `could not fetch ${keyLocation}: ${(e as Error).message}` };\n }\n if (!res.ok) return { ok: false, reason: `${keyLocation} returned ${res.status}` };\n const body = (await res.text()).trim();\n if (body !== key)\n return {\n ok: false,\n reason: `${keyLocation} does not contain the configured key (found ${body.length} chars)`,\n };\n return { ok: true };\n}\n\n/**\n * Submit one batch. Callers iterate `plan.batches` — the split is the planner's\n * job, so that what gets sent is decided in the pure layer and visible in `--dry`.\n */\nexport async function submitBatch(\n plan: IndexNowPlan,\n urls: string[],\n fetchImpl: typeof fetch = fetch,\n): Promise<SubmitResult> {\n const body = {\n host: plan.host,\n key: plan.key,\n keyLocation: plan.keyLocation,\n urlList: urls,\n };\n const res = await fetchImpl(plan.endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json; charset=utf-8' },\n body: JSON.stringify(body),\n });\n const message = explain(res.status);\n return { ok: res.ok, status: res.status, urls: urls.length, ...(message ? { message } : {}) };\n}\n","/**\n * Google Search Console — the two things its API will actually do.\n *\n * Worth stating plainly, because the gap between what people expect and what\n * exists is the whole reason this module is small: **there is no \"request\n * indexing\" endpoint.** The button in the Search Console UI is not exposed in the\n * API or anywhere else, and the sitemap ping endpoint was removed in 2023. What\n * remains is `sitemaps.submit` (write) and `urlInspection` (read).\n *\n * The Indexing API is deliberately not wired here. It is scoped to `JobPosting`\n * and `BroadcastEvent`; it accepts other URLs and discards them, and using it for\n * general pages violates its terms with the consumer's own GCP project on the\n * line. A toolchain should not ship that as a documented path.\n *\n * Auth is minted by hand rather than through `googleapis`, which would be an\n * enormous dependency in a CLI that installs into every consumer project, for two\n * endpoints. The exchange itself lives in `../google/token.ts` — it is shared with\n * the onboarding module, which needs the same token from a different grant.\n */\nimport {\n encodeSite,\n errorDetail,\n googleAccessToken,\n googleHeaders,\n SCOPES,\n type GoogleAuthLike,\n type ServiceAccount,\n} from '../google/token.ts';\n\nexport type { ServiceAccount } from '../google/token.ts';\n\n/**\n * Parse a service-account credential from its two supported sources.\n *\n * `VITOPS_GSC_SERVICE_ACCOUNT` holds the JSON inline (what a CI secret store\n * gives you); `GOOGLE_APPLICATION_CREDENTIALS` holds a path (Google's own\n * convention, and what a local `gcloud` setup already has). Supporting both means\n * neither environment has to be reshaped to fit the tool.\n */\nexport function parseServiceAccount(raw: string): ServiceAccount {\n let parsed: Partial<ServiceAccount>;\n try {\n parsed = JSON.parse(raw) as Partial<ServiceAccount>;\n } catch {\n throw new Error('service account is not valid JSON');\n }\n if (!parsed.client_email || !parsed.private_key)\n throw new Error('service account JSON is missing client_email or private_key');\n return { client_email: parsed.client_email, private_key: parsed.private_key };\n}\n\n/**\n * Exchange a service-account key for an access token (RS256 JWT bearer flow).\n *\n * `now` is a parameter so this is testable without mocking the clock.\n */\nexport function serviceAccountToken(\n account: ServiceAccount,\n fetchImpl: typeof fetch = fetch,\n now: number = Date.now(),\n): Promise<string> {\n return googleAccessToken(\n { kind: 'service-account', account, scope: SCOPES.webmasters },\n fetchImpl,\n now,\n );\n}\n\n/**\n * Re-submit a sitemap — the automated form of the manual resubmit in the UI.\n *\n * A `403` here almost always means `siteUrl` doesn't match the property exactly\n * (`sc-domain:acme.ca` vs `https://acme.ca/`) or the service account isn't an\n * owner of it, rather than that the sitemap is bad.\n */\nexport async function submitSitemap(\n auth: GoogleAuthLike,\n siteUrl: string,\n sitemapUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<{ ok: boolean; status: number; message?: string }> {\n const url = `https://www.googleapis.com/webmasters/v3/sites/${encodeSite(siteUrl)}/sitemaps/${encodeURIComponent(sitemapUrl)}`;\n const res = await fetchImpl(url, {\n method: 'PUT',\n headers: googleHeaders(auth),\n });\n if (res.ok) return { ok: true, status: res.status };\n const message = await errorDetail(res, (status) =>\n status === 403\n ? `403 — check that siteUrl \"${siteUrl}\" matches the Search Console property exactly and that the service account is an owner of it`\n : undefined,\n );\n return { ok: false, status: res.status, message };\n}\n\n/** What the URL Inspection API said about one page. */\nexport interface InspectionResult {\n url: string;\n /** Google's verdict, e.g. `PASS`, `NEUTRAL`, `FAIL`. */\n verdict?: string;\n /** e.g. `INDEXING_ALLOWED`, `BLOCKED_BY_ROBOTS_TXT`. */\n coverageState?: string;\n lastCrawlTime?: string;\n /** True when Google reports the page as indexed. */\n indexed: boolean;\n error?: string;\n}\n\n/**\n * Inspect one URL. **Read-only** — this reports what Google did, it cannot ask for\n * anything. Quota is 2000 queries/day per property, which is why the caller works\n * from an explicit `priorityUrls` list rather than the whole sitemap.\n */\nexport async function inspectUrl(\n auth: GoogleAuthLike,\n siteUrl: string,\n inspectionUrl: string,\n fetchImpl: typeof fetch = fetch,\n): Promise<InspectionResult> {\n const res = await fetchImpl(\n 'https://searchconsole.googleapis.com/v1/urlInspection/index:inspect',\n {\n method: 'POST',\n headers: googleHeaders(auth, { 'content-type': 'application/json' }),\n body: JSON.stringify({ inspectionUrl, siteUrl }),\n },\n );\n if (!res.ok)\n return { url: inspectionUrl, indexed: false, error: `${res.status}: ${await res.text()}` };\n\n const body = (await res.json()) as {\n inspectionResult?: {\n indexStatusResult?: { verdict?: string; coverageState?: string; lastCrawlTime?: string };\n };\n };\n const r = body.inspectionResult?.indexStatusResult ?? {};\n return {\n url: inspectionUrl,\n ...(r.verdict ? { verdict: r.verdict } : {}),\n ...(r.coverageState ? { coverageState: r.coverageState } : {}),\n ...(r.lastCrawlTime ? { lastCrawlTime: r.lastCrawlTime } : {}),\n // `PASS` is the only verdict that means indexed. `NEUTRAL` covers \"discovered,\n // not indexed\" and \"excluded by canonical\" — both are *not indexed*, and\n // reading them as success would make --check pass on the exact pages it exists\n // to catch.\n indexed: r.verdict === 'PASS',\n };\n}\n"],"mappings":";;;;;;AAeA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,iBAAiB;AAqD9B,MAAM,aAAa,MAAc,EAAE,QAAQ,QAAQ,EAAE;AAErD,SAAS,OAAO,KAAiC;CAC/C,IAAI;EACF,OAAO,IAAI,IAAI,GAAG,CAAC,CAAC;CACtB,QAAQ;EACN;CACF;AACF;AAEA,SAAS,MAAS,OAAY,MAAqB;CACjD,IAAI,MAAM,WAAW,GAAG,OAAO,CAAC;CAChC,MAAM,MAAa,CAAC;CACpB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,MAAM,IAAI,KAAK,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC;CAC9E,OAAO;AACT;;;;;;;;;AAUA,SAAgB,kBAAkB,QAA4C;CAC5E,IAAI,OAAO,YAAY,OAAO,OAAO;CACrC,IAAI,CAAC,OAAO,WAAW,OAAO;CAC9B,OAAO,GAAG,UAAU,OAAO,SAAS,EAAE;AACxC;;AAGA,SAAgB,mBAAmB,QAA4C;CAC7E,MAAM,WAAW,OAAO;CACxB,IAAI,CAAC,UAAU,OAAO;CACtB,IAAI,SAAS,aAAa,OAAO,SAAS;CAC1C,IAAI,CAAC,OAAO,WAAW,OAAO;CAC9B,OAAO,GAAG,UAAU,OAAO,SAAS,EAAE,GAAG,SAAS,IAAI;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AO,EAAE,YAAY,mBAAmB,UAAU,KAC1F;EAC/B,QAAQ;EACR,SAAS,cAAc,IAAI;CAC7B,CAAC;CACD,IAAI,IAAI,IAAI,OAAO;EAAE,IAAI;EAAM,QAAQ,IAAI;CAAO;CAClD,MAAM,UAAU,MAAM,YAAY,MAAM,WACtC,WAAW,MACP,6BAA6B,QAAQ,gGACrC,MACN;CACA,OAAO;EAAE,IAAI;EAAO,QAAQ,IAAI;EAAQ;CAAQ;AAClD;;;;;;AAoBA,eAAsB,WACpB,MACA,SACA,eACA,YAA0B,OACC;CAC3B,MAAM,MAAM,MAAM,UAChB,uEACA;EACE,QAAQ;EACR,SAAS,cAAc,MAAM,EAAE,gBAAgB,mBAAmB,CAAC;EACnE,MAAM,KAAK,UAAU;GAAE;GAAe;EAAQ,CAAC;CACjD,CACF;CACA,IAAI,CAAC,IAAI,IACP,OAAO;EAAE,KAAK;EAAe,SAAS;EAAO,OAAO,GAAG,IAAI,OAAO,IAAI,MAAM,IAAI,KAAK;CAAI;CAO3F,MAAM,KAAI,MALU,IAAI,KAAK,EAKf,CAAC,kBAAkB,qBAAqB,CAAC;CACvD,OAAO;EACL,KAAK;EACL,GAAI,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,IAAI,CAAC;EAC1C,GAAI,EAAE,gBAAgB,EAAE,eAAe,EAAE,cAAc,IAAI,CAAC;EAC5D,GAAI,EAAE,gBAAgB,EAAE,eAAe,EAAE,cAAc,IAAI,CAAC;EAK5D,SAAS,EAAE,YAAY;CACzB;AACF"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
|
|
4
|
+
//#region src/json-store.ts
|
|
5
|
+
/**
|
|
6
|
+
* Read/write helpers shared by every `.vitops/*.json` cache
|
|
7
|
+
* (`indexing/snapshot.ts`, `reviews/cache.ts`, `media/manifest.ts`).
|
|
8
|
+
*
|
|
9
|
+
* All three follow the same rule: a corrupt or wrong-version file reads as
|
|
10
|
+
* absent, never as an empty-but-valid record — the alternative is
|
|
11
|
+
* indistinguishable from "there is genuinely nothing here" and silently ships
|
|
12
|
+
* an empty result. Each module keeps its own `toX` sorter (they differ in
|
|
13
|
+
* which field holds the record and how its entries are ordered); only the
|
|
14
|
+
* read/write mechanics are shared here.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Read a versioned cache file, or `undefined` when there isn't a usable one
|
|
18
|
+
* (missing, unparsable, wrong version, or `key`'s field isn't an object).
|
|
19
|
+
*/
|
|
20
|
+
function readVersioned(path, key) {
|
|
21
|
+
if (!existsSync(path)) return void 0;
|
|
22
|
+
try {
|
|
23
|
+
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
24
|
+
if (raw?.version !== 1 || typeof raw[key] !== "object" || raw[key] === null) return void 0;
|
|
25
|
+
return raw;
|
|
26
|
+
} catch {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Write a cache file, creating its directory. Call only once the value is final. */
|
|
31
|
+
function writeVersioned(path, value) {
|
|
32
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
33
|
+
writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
//#endregion
|
|
37
|
+
export { writeVersioned as n, readVersioned as t };
|
|
38
|
+
//# sourceMappingURL=json-store-30CFCbZZ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-store-30CFCbZZ.mjs","names":[],"sources":["../src/json-store.ts"],"sourcesContent":["/**\n * Read/write helpers shared by every `.vitops/*.json` cache\n * (`indexing/snapshot.ts`, `reviews/cache.ts`, `media/manifest.ts`).\n *\n * All three follow the same rule: a corrupt or wrong-version file reads as\n * absent, never as an empty-but-valid record — the alternative is\n * indistinguishable from \"there is genuinely nothing here\" and silently ships\n * an empty result. Each module keeps its own `toX` sorter (they differ in\n * which field holds the record and how its entries are ordered); only the\n * read/write mechanics are shared here.\n */\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\n/** A cache file's shape: a version tag plus one record field, keyed by `key`. */\ntype Versioned<Key extends string> = { version: 1 } & Record<Key, Record<string, unknown> | null>;\n\n/**\n * Read a versioned cache file, or `undefined` when there isn't a usable one\n * (missing, unparsable, wrong version, or `key`'s field isn't an object).\n */\nexport function readVersioned<T extends Versioned<Key>, Key extends string>(\n path: string,\n key: Key,\n): T | undefined {\n if (!existsSync(path)) return undefined;\n try {\n const raw = JSON.parse(readFileSync(path, 'utf8')) as T;\n if (raw?.version !== 1 || typeof raw[key] !== 'object' || raw[key] === null) return undefined;\n return raw;\n } catch {\n return undefined;\n }\n}\n\n/** Write a cache file, creating its directory. Call only once the value is final. */\nexport function writeVersioned(path: string, value: unknown): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,cACd,MACA,KACe;CACf,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO;CAC9B,IAAI;EACF,MAAM,MAAM,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;EACjD,IAAI,KAAK,YAAY,KAAK,OAAO,IAAI,SAAS,YAAY,IAAI,SAAS,MAAM,OAAO;EACpF,OAAO;CACT,QAAQ;EACN;CACF;AACF;;AAGA,SAAgB,eAAe,MAAc,OAAsB;CACjE,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,cAAc,MAAM,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,GAAG;AAC3D"}
|
package/dist/media/index.d.mts
CHANGED
|
@@ -65,7 +65,6 @@ interface MediaConfig {
|
|
|
65
65
|
}
|
|
66
66
|
/** A discovered source video. */
|
|
67
67
|
interface MediaSource {
|
|
68
|
-
/** Absolute path on disk. */
|
|
69
68
|
path: string;
|
|
70
69
|
/**
|
|
71
70
|
* Path relative to the raw directory, POSIX-separated — the manifest key.
|
|
@@ -101,7 +100,6 @@ interface MediaPlan {
|
|
|
101
100
|
interface MediaManifestEntry {
|
|
102
101
|
/** `MediaSource.hash` at the time of encoding. */
|
|
103
102
|
source: string;
|
|
104
|
-
/** Settings hash at the time of encoding. */
|
|
105
103
|
settings: string;
|
|
106
104
|
/** Output paths relative to the output directory. */
|
|
107
105
|
outputs: string[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/media/types.ts","../../src/media/discover.ts","../../src/media/plan.ts","../../src/media/ffmpeg.ts","../../src/media/manifest.ts","../../src/media/index.ts"],"mappings":";;AAUA;;;;AAAsB;AAGtB;;;KAHY,UAAA;AAG4B;AAAA,cAA3B,eAAA,EAAiB,UAAU;;cAG3B,UAAA,EAAY,MAAM,CAAC,UAAA;;AAAU;AAe1C;;;;AAA4B;AAG5B;;cAHa,eAAA;;UAGI,WAAA;EAgBf;;;;;;EATA,QAAA;EA8BoB;AAItB;;;;;;;EAzBE,GAAA;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/media/types.ts","../../src/media/discover.ts","../../src/media/plan.ts","../../src/media/ffmpeg.ts","../../src/media/manifest.ts","../../src/media/index.ts"],"mappings":";;AAUA;;;;AAAsB;AAGtB;;;KAHY,UAAA;AAG4B;AAAA,cAA3B,eAAA,EAAiB,UAAU;;cAG3B,UAAA,EAAY,MAAM,CAAC,UAAA;;AAAU;AAe1C;;;;AAA4B;AAG5B;;cAHa,eAAA;;UAGI,WAAA;EAgBf;;;;;;EATA,QAAA;EA8BoB;AAItB;;;;;;;EAzBE,GAAA;EAkCI;AAIN;;;;;EA/BE,UAAA;EAkCA;;AAAI;AAIN;EAjCE,KAAA;;;;;;;EAOA,UAAA;EAgCA;EA9BA,OAAA,GAAU,UAAU;AAAA;AAkCtB;AAAA,UA9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e,IAAA,EAAM,SAAA,KAAY,QAAQ;AF7DtD;AAAA,iBEgEgB,UAAA,CAAW,IAAe,EAAT,SAAS;;;AFrJ1C;;;;AAAsB;AAGtB;;;;AAHA,iBG2BgB,aAAA,IAAiB,OAAO;AHrBxC;;;;AAA0C;AAe1C;;;AAfA,iBG0FsB,UAAA,CACpB,KAAA,UACA,MAAA,UACA,MAAA,EAAQ,mBAAA,GACP,OAAO;AH/EkB;AAG5B;;;;;;;AAH4B,iBG0IN,SAAA,CACpB,KAAA,UACA,MAAA,UACA,MAAA,EAAQ,mBAAA,GACP,OAAO;;iBAyBY,aAAA,CACpB,KAAA,UACA,MAAA,UACA,MAAA,EAAQ,mBAAA,GACP,OAAO;;;AH7L8B;AAAA,cIA3B,mBAAA;;;;AJG6B;AAe1C;;;;iBIRgB,YAAA,CAAa,IAAA,WAAe,aAAa;AJWzD;AAAA,iBINgB,UAAA,CAAW,OAAA,EAAS,MAAA,SAAe,kBAAA,IAAsB,aAAA;;;;;;;;iBAgBzD,aAAA,CAAc,IAAA,UAAc,QAAA,EAAU,aAAa;;;UCrBlD,mBAAA;ELbK;EKepB,GAAA;ELfoB;EKiBpB,GAAA;EACA,MAAA,GAAS,WAAW;ELfgD;EKiBpE,QAAA;ELjBsC;EKmBtC,KAAA;ELhBW;EKkBX,GAAA;;EAEA,UAAA,KAAe,OAAA;AAAA;AAAA,UAGA,kBAAA;EACf,IAAA,EAAM,SAAS;;EAEf,OAAA;ELX0B;EKa1B,OAAA;AAAA;;;;;;;;iBAUoB,YAAA,CAAa,OAAA,EAAS,mBAAA,GAAsB,OAAA,CAAQ,kBAAA"}
|
package/dist/media/index.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { n as writeVersioned, t as readVersioned } from "../json-store-30CFCbZZ.mjs";
|
|
2
|
+
import { createReadStream, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
2
3
|
import { promisify } from "node:util";
|
|
3
4
|
import { execFile } from "node:child_process";
|
|
4
5
|
import { dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
@@ -253,15 +254,6 @@ async function extractPoster(input, output, config) {
|
|
|
253
254
|
|
|
254
255
|
//#endregion
|
|
255
256
|
//#region src/media/manifest.ts
|
|
256
|
-
/**
|
|
257
|
-
* The cache — what makes a second run free.
|
|
258
|
-
*
|
|
259
|
-
* A committed artifact, unlike `indexing/`'s snapshot: the recommended layout
|
|
260
|
-
* checks in both the processed outputs and this file, so CI never needs ffmpeg
|
|
261
|
-
* and the outputs only change when someone deliberately re-encodes. That is why
|
|
262
|
-
* `writeManifest` sorts and carries no timestamp — an unchanged run has to produce
|
|
263
|
-
* a byte-identical file, or every build shows up as a diff.
|
|
264
|
-
*/
|
|
265
257
|
/** Default location, relative to the consumer's project root. */
|
|
266
258
|
const MEDIA_MANIFEST_PATH = ".vitops/media-manifest.json";
|
|
267
259
|
/**
|
|
@@ -273,14 +265,7 @@ const MEDIA_MANIFEST_PATH = ".vitops/media-manifest.json";
|
|
|
273
265
|
* would encode, and the build would reference outputs that were never written.
|
|
274
266
|
*/
|
|
275
267
|
function readManifest(path) {
|
|
276
|
-
|
|
277
|
-
try {
|
|
278
|
-
const raw = JSON.parse(readFileSync(path, "utf8"));
|
|
279
|
-
if (raw?.version !== 1 || typeof raw.entries !== "object" || raw.entries === null) return void 0;
|
|
280
|
-
return raw;
|
|
281
|
-
} catch {
|
|
282
|
-
return;
|
|
283
|
-
}
|
|
268
|
+
return readVersioned(path, "entries");
|
|
284
269
|
}
|
|
285
270
|
/** Build a manifest with its keys and output lists in a stable order. */
|
|
286
271
|
function toManifest(entries) {
|
|
@@ -305,8 +290,7 @@ function toManifest(entries) {
|
|
|
305
290
|
* result is a missing video that no rebuild ever fixes.
|
|
306
291
|
*/
|
|
307
292
|
function writeManifest(path, manifest) {
|
|
308
|
-
|
|
309
|
-
writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
293
|
+
writeVersioned(path, manifest);
|
|
310
294
|
}
|
|
311
295
|
|
|
312
296
|
//#endregion
|