@apocaliss92/addon-series-scraper 0.0.0-stage → 0.1.21

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.
@@ -0,0 +1,316 @@
1
+ import { createRequire as __scraperCreateRequire } from "node:module";
2
+ __scraperCreateRequire(import.meta.url);
3
+ import { S as require_Reflect, a as errorText, i as HOST_LOG_TAGS, v as require_dist } from "./proxy-Btrb1iBN.js";
4
+ import { copyFile, mkdir, readFile, readdir, stat } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { n as SettingsSecretStore, t as RecordsStateStore } from "./state-store-DT6l2jtx.js";
7
+ require_Reflect();
8
+ var import_dist = require_dist();
9
+ /** Where the operator drops the Docker data directory, under the addon's own data directory. */
10
+ var IMPORT_DIR_NAME = "import";
11
+ /** Entries of a Docker data directory that are never carried over, by the name they have there. */
12
+ var SKIPPED_ENTRIES = [
13
+ {
14
+ entry: "chrome-profile",
15
+ name: "chrome-profiles"
16
+ },
17
+ {
18
+ entry: "chrome-profiles",
19
+ name: "chrome-profiles"
20
+ },
21
+ {
22
+ entry: "logs",
23
+ name: "logs"
24
+ },
25
+ {
26
+ entry: "captcha-debug",
27
+ name: "captcha-debug"
28
+ },
29
+ {
30
+ entry: "partial-downloads",
31
+ name: "partial-downloads"
32
+ },
33
+ {
34
+ entry: "partial-downloads.json",
35
+ name: "partial-downloads"
36
+ },
37
+ {
38
+ entry: "captcha-challenges.json",
39
+ name: "captcha-challenges"
40
+ }
41
+ ];
42
+ /** Collections whose rows only make sense next to the old container's disk. */
43
+ var NOT_IMPORTED = ["partial-downloads", "captcha-challenges"];
44
+ /** Said with every plan: these values are copied exactly as the Docker file holds them. */
45
+ var IMPORT_NOTES = ["plugin-settings are imported as stored (plain values)"];
46
+ /** A refused or failed import: a code the page can act on and a message free of values. */
47
+ var ImportError = class extends Error {
48
+ code;
49
+ plan;
50
+ constructor(code, message, plan) {
51
+ super(message);
52
+ this.code = code;
53
+ this.plan = plan;
54
+ }
55
+ };
56
+ /** True when every key of a stored settings document equals the core's default: nobody edited it. */
57
+ function isDefaultSettings(value) {
58
+ if (isEmpty(value)) return true;
59
+ if (!isObject(value)) return false;
60
+ const defaults = new Map(Object.entries(import_dist.DEFAULT_SETTINGS));
61
+ return Object.entries(value).every(([key, entry]) => defaults.has(key) && canonical(defaults.get(key)) === canonical(entry));
62
+ }
63
+ /**
64
+ * Does `existing` hold anything an import must not silently replace? User data (table, tags,
65
+ * webhooks, sites, history, failed episodes, network exits) and the plugin / network settings
66
+ * count when non-empty; the settings document counts only when it differs from the defaults.
67
+ */
68
+ function holdsData(name, existing) {
69
+ if (name === "settings") return !isDefaultSettings(existing);
70
+ return !isEmpty(existing);
71
+ }
72
+ function isObject(value) {
73
+ return typeof value === "object" && value !== null && !Array.isArray(value);
74
+ }
75
+ function isEmpty(value) {
76
+ if (value === void 0 || value === null) return true;
77
+ if (Array.isArray(value)) return value.length === 0;
78
+ return isObject(value) && Object.keys(value).length === 0;
79
+ }
80
+ /** JSON with sorted keys: two values that mean the same compare equal whatever their key order. */
81
+ function canonical(value) {
82
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
83
+ if (isObject(value)) return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
84
+ return JSON.stringify(value) ?? "null";
85
+ }
86
+ /** How many things a collection holds: the list's length, or the keys of an object. */
87
+ function countOf(value) {
88
+ if (Array.isArray(value)) return value.length;
89
+ if (isObject(value)) {
90
+ const keys = Object.keys(value);
91
+ const only = keys.length === 1 ? value[keys[0] ?? ""] : void 0;
92
+ return Array.isArray(only) ? only.length : keys.length;
93
+ }
94
+ return value === void 0 || value === null ? 0 : 1;
95
+ }
96
+ async function exists(path) {
97
+ try {
98
+ await stat(path);
99
+ return true;
100
+ } catch {
101
+ return false;
102
+ }
103
+ }
104
+ async function sameBytes(a, b) {
105
+ try {
106
+ const [left, right] = await Promise.all([readFile(a), readFile(b)]);
107
+ return left.equals(right);
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+ /**
113
+ * Import of a scraper container's data directory (`<dataDir>/import`) into what the embedded
114
+ * host keeps: the same record kinds (through `RecordsStateStore`) and the same keychain path
115
+ * (through `SettingsSecretStore`), so the next embedded boot hydrates exactly this.
116
+ */
117
+ var DockerImport = class {
118
+ deps;
119
+ busy = false;
120
+ constructor(deps) {
121
+ this.deps = deps;
122
+ }
123
+ get sourceDir() {
124
+ return join(this.deps.dataDir, IMPORT_DIR_NAME);
125
+ }
126
+ get pluginsDir() {
127
+ return join(this.deps.dataDir, "plugins");
128
+ }
129
+ /** Counts and names of what an apply would carry over; writes nothing and reads no value out. */
130
+ async dryRun() {
131
+ const { plan } = await this.prepare();
132
+ this.deps.logger.info("series-scraper import: dry run", {
133
+ tags: HOST_LOG_TAGS,
134
+ meta: {
135
+ collections: Object.fromEntries(Object.entries(plan.collections).map(([name, { count }]) => [name, count])),
136
+ secrets: plan.secrets.length,
137
+ plugins: plan.plugins.length,
138
+ skipped: plan.skipped,
139
+ conflicts: plan.conflicts
140
+ }
141
+ });
142
+ return plan;
143
+ }
144
+ async apply(options) {
145
+ const { logger } = this.deps;
146
+ if (this.deps.embeddedRunning()) {
147
+ logger.warn("series-scraper import: refused, the embedded scraper is running", { tags: HOST_LOG_TAGS });
148
+ throw new ImportError("embedded-running", "The embedded scraper is running and holds its state in memory. Switch to the external backend, import, then switch back.");
149
+ }
150
+ const { plan, layout, state, secrets } = await this.prepare();
151
+ const { conflicts } = plan;
152
+ if (conflicts.collections.length + conflicts.secrets.length + conflicts.plugins.length > 0 && !options.overwrite) {
153
+ logger.warn("series-scraper import: refused, the embedded store already holds data", {
154
+ tags: HOST_LOG_TAGS,
155
+ meta: { conflicts }
156
+ });
157
+ throw new ImportError("target-not-empty", "The embedded store already holds different data. Import again with overwrite to replace it.", plan);
158
+ }
159
+ const changed = /* @__PURE__ */ new Set();
160
+ for (const name of import_dist.STATE_COLLECTIONS) {
161
+ const incoming = layout.collections[name];
162
+ if (incoming === void 0 || NOT_IMPORTED.includes(name)) continue;
163
+ if (canonical(state.load(name)) === canonical(incoming)) continue;
164
+ state.save(name, incoming);
165
+ changed.add(name);
166
+ }
167
+ const setSecrets = [];
168
+ const unchangedSecrets = [];
169
+ for (const [name, value] of Object.entries(layout.secrets)) {
170
+ if (secrets.get(name) === value) {
171
+ unchangedSecrets.push(name);
172
+ continue;
173
+ }
174
+ secrets.set(name, value);
175
+ setSecrets.push(name);
176
+ }
177
+ const unwritten = [...await state.flush(), ...await secrets.flush()];
178
+ if (unwritten.length > 0) {
179
+ logger.error("series-scraper import: some state could not be written", {
180
+ tags: HOST_LOG_TAGS,
181
+ meta: { unwritten }
182
+ });
183
+ throw new ImportError("import-write-failed", `Some state could not be written: ${unwritten.join(", ")}. Apply again to retry.`);
184
+ }
185
+ const copied = [];
186
+ const unchangedPlugins = [];
187
+ let copying = "";
188
+ try {
189
+ if (layout.plugins.length > 0) await mkdir(this.pluginsDir, { recursive: true });
190
+ for (const name of layout.plugins) {
191
+ copying = name;
192
+ const target = join(this.pluginsDir, name);
193
+ if (await sameBytes(join(this.sourceDir, "plugins", name), target)) {
194
+ unchangedPlugins.push(name);
195
+ continue;
196
+ }
197
+ await copyFile(join(this.sourceDir, "plugins", name), target);
198
+ copied.push(name);
199
+ }
200
+ } catch (error) {
201
+ logger.error("series-scraper import: a plugin could not be copied", {
202
+ tags: HOST_LOG_TAGS,
203
+ meta: {
204
+ file: copying,
205
+ copied: copied.length,
206
+ reason: errorText(error)
207
+ }
208
+ });
209
+ throw new ImportError("import-plugin-failed", `The state was written, but the plugin ${copying === "" ? "directory" : `"${copying}"`} could not be copied. Apply again to retry.`);
210
+ }
211
+ const outcome = {
212
+ collections: Object.fromEntries(Object.entries(plan.collections).map(([name, { count }]) => [name, {
213
+ count,
214
+ changed: changed.has(name)
215
+ }])),
216
+ secrets: {
217
+ set: setSecrets,
218
+ unchanged: unchangedSecrets
219
+ },
220
+ plugins: {
221
+ copied,
222
+ unchanged: unchangedPlugins
223
+ },
224
+ skipped: plan.skipped
225
+ };
226
+ logger.info("series-scraper import: applied", {
227
+ tags: HOST_LOG_TAGS,
228
+ meta: {
229
+ overwrite: options.overwrite,
230
+ collectionsWritten: [...changed],
231
+ secretsSet: setSecrets.length,
232
+ secretsUnchanged: unchangedSecrets.length,
233
+ pluginsCopied: copied.length,
234
+ pluginsUnchanged: unchangedPlugins.length,
235
+ skipped: plan.skipped
236
+ }
237
+ });
238
+ return outcome;
239
+ }
240
+ /** Run one import at a time: an apply and a dry run never interleave their reads and writes. */
241
+ async exclusive(job) {
242
+ if (this.busy) throw new ImportError("import-busy", "An import is already running.");
243
+ this.busy = true;
244
+ try {
245
+ return await job();
246
+ } finally {
247
+ this.busy = false;
248
+ }
249
+ }
250
+ async prepare() {
251
+ const { records, settings, logger, writeBehind } = this.deps;
252
+ if (!await exists(this.sourceDir)) throw new ImportError("import-dir-missing", `Nothing to import: copy the scraper's data directory into the addon's "${IMPORT_DIR_NAME}" directory first.`);
253
+ let layout;
254
+ try {
255
+ layout = (0, import_dist.readDockerLayout)(this.sourceDir);
256
+ } catch (error) {
257
+ logger.warn("series-scraper import: the data directory could not be read", {
258
+ tags: HOST_LOG_TAGS,
259
+ meta: { reason: errorText(error) }
260
+ });
261
+ throw new ImportError("import-unreadable", errorText(error));
262
+ }
263
+ const state = new RecordsStateStore({
264
+ records,
265
+ logger,
266
+ writeBehind
267
+ });
268
+ await state.hydrate();
269
+ const secrets = new SettingsSecretStore({
270
+ settings,
271
+ records,
272
+ logger,
273
+ writeBehind
274
+ });
275
+ await secrets.hydrate();
276
+ const collections = {};
277
+ const conflictingCollections = [];
278
+ for (const name of import_dist.STATE_COLLECTIONS) {
279
+ const incoming = layout.collections[name];
280
+ if (incoming === void 0 || NOT_IMPORTED.includes(name)) continue;
281
+ collections[name] = { count: countOf(incoming) };
282
+ const existing = state.load(name);
283
+ if (holdsData(name, existing) && canonical(existing) !== canonical(incoming)) conflictingCollections.push(name);
284
+ }
285
+ const secretNames = Object.keys(layout.secrets).sort();
286
+ const conflictingSecrets = secretNames.filter((name) => {
287
+ const existing = secrets.get(name);
288
+ return existing !== void 0 && existing !== layout.secrets[name];
289
+ });
290
+ const conflictingPlugins = [];
291
+ for (const name of layout.plugins) {
292
+ const target = join(this.pluginsDir, name);
293
+ if (await exists(target) && !await sameBytes(join(this.sourceDir, "plugins", name), target)) conflictingPlugins.push(name);
294
+ }
295
+ const present = new Set(await readdir(this.sourceDir));
296
+ const skipped = [...new Set(SKIPPED_ENTRIES.filter(({ entry }) => present.has(entry)).map(({ name }) => name))];
297
+ return {
298
+ plan: {
299
+ collections,
300
+ secrets: secretNames,
301
+ plugins: layout.plugins,
302
+ skipped,
303
+ notes: IMPORT_NOTES,
304
+ conflicts: {
305
+ collections: conflictingCollections,
306
+ secrets: conflictingSecrets,
307
+ plugins: conflictingPlugins
308
+ }
309
+ },
310
+ layout,
311
+ state,
312
+ secrets
313
+ };
314
+ }
315
+ };
316
+ export { DockerImport, IMPORT_DIR_NAME, IMPORT_NOTES, ImportError };