-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathpopulate-cache.ts
More file actions
78 lines (67 loc) · 2.35 KB
/
populate-cache.ts
File metadata and controls
78 lines (67 loc) · 2.35 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
import { spawnSync } from "node:child_process";
import { existsSync } from "node:fs";
import path from "node:path";
import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
import logger from "@opennextjs/aws/logger.js";
import type {
IncludedIncrementalCache,
IncludedTagCache,
LazyLoadedOverride,
OpenNextConfig,
} from "@opennextjs/aws/types/open-next.js";
import type { IncrementalCache, TagCache } from "@opennextjs/aws/types/overrides.js";
export type CacheBindingMode = "local" | "remote";
async function resolveCacheName(
value:
| IncludedIncrementalCache
| IncludedTagCache
| LazyLoadedOverride<IncrementalCache>
| LazyLoadedOverride<TagCache>
) {
return typeof value === "function" ? (await value()).name : value;
}
function runWrangler(opts: BuildOptions, mode: CacheBindingMode, args: string[]) {
const result = spawnSync(
opts.packager,
["exec", "wrangler", ...args, mode === "remote" && "--remote"].filter((v): v is string => !!v),
{
shell: true,
stdio: ["ignore", "ignore", "inherit"],
}
);
if (result.status !== 0) {
logger.error("Failed to populate cache");
process.exit(1);
} else {
logger.info("Successfully populated cache");
}
}
export async function populateCache(opts: BuildOptions, config: OpenNextConfig, mode: CacheBindingMode) {
const { incrementalCache, tagCache } = config.default.override ?? {};
if (!existsSync(opts.outputDir)) {
logger.error("Unable to populate cache: Open Next build not found");
process.exit(1);
}
if (!config.dangerous?.disableIncrementalCache && incrementalCache) {
logger.info("Incremental cache does not need populating");
}
if (!config.dangerous?.disableTagCache && !config.dangerous?.disableIncrementalCache && tagCache) {
const name = await resolveCacheName(tagCache);
switch (name) {
case "d1-tag-cache": {
logger.info("\nPopulating D1 tag cache...");
runWrangler(opts, mode, [
"d1 execute",
"NEXT_CACHE_D1",
`--file ${JSON.stringify(path.join(opts.outputDir, "cloudflare/cache-assets-manifest.sql"))}`,
]);
break;
}
default:
logger.info("Tag cache does not need populating");
}
}
}
export function isCacheBindingMode(v: string | undefined): v is CacheBindingMode {
return !!v && ["local", "remote"].includes(v);
}