@composable-os/cli 0.0.0-stage → 0.1.0-beta.7
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/LICENSE +109 -0
- package/README.md +24 -2
- package/dist/blocks-HVTAQ5W2.js +233 -0
- package/dist/chunk-2ABSVMGB.js +13 -0
- package/dist/chunk-2P4AZTFL.js +358 -0
- package/dist/chunk-2S7375SC.js +802 -0
- package/dist/chunk-5KSXSK7Y.js +47 -0
- package/dist/chunk-6UWRT4VM.js +220 -0
- package/dist/chunk-BEKL3CA2.js +28975 -0
- package/dist/chunk-E5JLTLRM.js +50 -0
- package/dist/chunk-HDIOVFAZ.js +544 -0
- package/dist/chunk-KGHA67HG.js +765 -0
- package/dist/chunk-MAXLUQKB.js +1287 -0
- package/dist/chunk-MINQ46RU.js +16485 -0
- package/dist/chunk-STJZJIRA.js +11378 -0
- package/dist/chunk-VL62IMBN.js +1423 -0
- package/dist/chunk-X6I2LWB3.js +24319 -0
- package/dist/chunk-Y7PQ7NIL.js +1178 -0
- package/dist/chunk-ZRWF6QZS.js +2357 -0
- package/dist/cli-BRSACHSG.js +31393 -0
- package/dist/cli-XHC6QBQW.js +121 -0
- package/dist/cli.js +25 -0
- package/dist/client-repo-G55G4OLV.js +55 -0
- package/dist/create.js +25 -0
- package/dist/fields-64BQJA62.js +48 -0
- package/dist/invoke-5SR5ZWW7.js +26 -0
- package/dist/person-AZFEPZOE.js +58 -0
- package/dist/platform/migrations/0001_init.sql +59 -0
- package/dist/platform/migrations/0002_users_settings.sql +34 -0
- package/dist/platform/migrations/0003_people_organisations.sql +225 -0
- package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
- package/dist/platform/migrations/0005_views_audit.sql +79 -0
- package/dist/platform/migrations/0006_search.sql +223 -0
- package/dist/platform/migrations/0007_crm_views.sql +141 -0
- package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
- package/dist/platform/migrations/0010_approval_queue.sql +90 -0
- package/dist/platform/migrations/0011_connected_apps.sql +36 -0
- package/dist/platform/migrations/0020_extensions.sql +373 -0
- package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
- package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
- package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
- package/dist/platform/migrations/0061_audit_retention.sql +95 -0
- package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
- package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
- package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
- package/dist/platform/migrations/0065_storage_stats.sql +13 -0
- package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
- package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
- package/dist/platform/migrations/0100_stage_history.sql +54 -0
- package/dist/platform/migrations/0110_integrations.sql +103 -0
- package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
- package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
- package/dist/platform/migrations/0130_automations.sql +113 -0
- package/dist/platform/migrations/0131_notifications.sql +29 -0
- package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
- package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
- package/dist/platform/migrations/0160_releases.sql +41 -0
- package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
- package/dist/platform/migrations/0170_automation_connections.sql +32 -0
- package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
- package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
- package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
- package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
- package/dist/platform/migrations/0210_daily_digest.sql +33 -0
- package/dist/platform/migrations/0220_entitlements.sql +13 -0
- package/dist/platform/migrations/0221_support_grants.sql +33 -0
- package/dist/platform/migrations/0250_judge.sql +11 -0
- package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
- package/dist/platform/migrations/0252_judge_usage.sql +14 -0
- package/dist/platform/migrations/0255_summary_checks.sql +9 -0
- package/dist/platform/migrations/0256_outbound_check.sql +9 -0
- package/dist/platform/migrations/0260_ai_usage.sql +20 -0
- package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
- package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
- package/dist/platform/migrations/0320_duplicates.sql +41 -0
- package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
- package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
- package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
- package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
- package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
- package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
- package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
- package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
- package/dist/platform/migrations/0362_voice_usage.sql +17 -0
- package/dist/platform/migrations/0365_routines.sql +38 -0
- package/dist/platform/migrations/0370_approval_execution.sql +20 -0
- package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
- package/dist/platform/migrations/0380_rec_views.sql +94 -0
- package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
- package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
- package/dist/platform/migrations/0402_erase_requests.sql +34 -0
- package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
- package/dist/platform/migrations/0411_device_sessions.sql +33 -0
- package/dist/platform/migrations/0420_transition_history.sql +100 -0
- package/dist/platform/migrations/0421_orders.sql +134 -0
- package/dist/platform/migrations/0422_order_payments.sql +109 -0
- package/dist/platform/migrations/0440_capacity.sql +100 -0
- package/dist/platform/migrations/0441_capacity_views.sql +40 -0
- package/dist/platform/migrations/0450_order_grants.sql +21 -0
- package/dist/platform/migrations/0451_pack_roles.sql +18 -0
- package/dist/platform/migrations/0460_content.sql +59 -0
- package/dist/platform/migrations/0461_media.sql +52 -0
- package/dist/platform/migrations/0470_publish_versions.sql +36 -0
- package/dist/platform/migrations/0471_permission_grants.sql +18 -0
- package/dist/platform/migrations/0490_staff_invites.sql +40 -0
- package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
- package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
- package/dist/platform/migrations/0500_published_media_field.sql +25 -0
- package/dist/platform/migrations/0501_import_keys.sql +23 -0
- package/dist/platform/sdk/automation-check.ts +534 -0
- package/dist/platform/sdk/automation.ts +743 -0
- package/dist/platform/sdk/behaviour.ts +215 -0
- package/dist/platform/sdk/capacity.ts +112 -0
- package/dist/platform/sdk/contract.ts +766 -0
- package/dist/platform/sdk/document.ts +788 -0
- package/dist/platform/sdk/field-types.ts +106 -0
- package/dist/platform/sdk/formula/ast.ts +72 -0
- package/dist/platform/sdk/formula/compile.ts +454 -0
- package/dist/platform/sdk/formula/index.ts +4 -0
- package/dist/platform/sdk/formula/parser.ts +417 -0
- package/dist/platform/sdk/index.ts +33 -0
- package/dist/platform/sdk/manifest.ts +1484 -0
- package/dist/platform/sdk/media.ts +46 -0
- package/dist/platform/sdk/permissions.ts +60 -0
- package/dist/platform/sdk/renamed.ts +63 -0
- package/dist/platform/sdk/rich-text-fixture.ts +68 -0
- package/dist/platform/sdk/rich-text.ts +173 -0
- package/dist/platform/sdk/runtime.ts +410 -0
- package/dist/platform/sdk/sellable.ts +396 -0
- package/dist/platform/sdk/slug.ts +25 -0
- package/dist/platform/sdk/states.ts +162 -0
- package/dist/platform/sdk/testing.ts +836 -0
- package/dist/products-2H5DR232.js +11 -0
- package/dist/run-4JNFLYXV.js +847 -0
- package/dist/src-J27WXNLY.js +270 -0
- package/dist/src-SSVOBH6L.js +31 -0
- package/dist/token-MOJUA2U6.js +70 -0
- package/dist/token-util-TENRN4V7.js +6 -0
- package/package.json +33 -4
|
@@ -0,0 +1,847 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
IMAGE_SCHEMA,
|
|
4
|
+
RICH_TEXT_SCHEMA,
|
|
5
|
+
SLUG_MAX,
|
|
6
|
+
SLUG_RE,
|
|
7
|
+
mediaProblem,
|
|
8
|
+
slugify,
|
|
9
|
+
validateDocument
|
|
10
|
+
} from "./chunk-X6I2LWB3.js";
|
|
11
|
+
import "./chunk-5KSXSK7Y.js";
|
|
12
|
+
|
|
13
|
+
// src/content-import/run.ts
|
|
14
|
+
import { execFile } from "node:child_process";
|
|
15
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
16
|
+
import { createServer } from "node:http";
|
|
17
|
+
import { hostname } from "node:os";
|
|
18
|
+
import { join, resolve } from "node:path";
|
|
19
|
+
|
|
20
|
+
// ../client/src/binding.ts
|
|
21
|
+
var SESSION_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
22
|
+
|
|
23
|
+
// ../client/src/errors.ts
|
|
24
|
+
var ApiError = class extends Error {
|
|
25
|
+
constructor(code, message, status, details) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.code = code;
|
|
28
|
+
this.status = status;
|
|
29
|
+
this.details = details;
|
|
30
|
+
}
|
|
31
|
+
code;
|
|
32
|
+
status;
|
|
33
|
+
details;
|
|
34
|
+
name = "ApiError";
|
|
35
|
+
};
|
|
36
|
+
var NetworkError = class extends Error {
|
|
37
|
+
constructor(message, cause) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.cause = cause;
|
|
40
|
+
}
|
|
41
|
+
cause;
|
|
42
|
+
name = "NetworkError";
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
// ../client/src/session.ts
|
|
46
|
+
async function post(fetcher, url, body, headers = {}) {
|
|
47
|
+
let response;
|
|
48
|
+
try {
|
|
49
|
+
response = await fetcher(url, {
|
|
50
|
+
method: "POST",
|
|
51
|
+
headers: { "content-type": "application/json", ...headers },
|
|
52
|
+
body: JSON.stringify(body)
|
|
53
|
+
});
|
|
54
|
+
} catch (error) {
|
|
55
|
+
throw new NetworkError("Could not reach the host to sign in", error);
|
|
56
|
+
}
|
|
57
|
+
const parsed = JSON.parse(await response.text());
|
|
58
|
+
if (response.status === 200 && parsed.data) return parsed.data;
|
|
59
|
+
throw new ApiError(
|
|
60
|
+
parsed.error?.code ?? "internal",
|
|
61
|
+
parsed.error?.message ?? `The host answered ${response.status}`,
|
|
62
|
+
response.status,
|
|
63
|
+
parsed.error?.details
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
function tokenSession(options) {
|
|
67
|
+
const base = options.baseUrl.replace(/\/+$/, "");
|
|
68
|
+
const fetcher = options.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
69
|
+
const early = options.refreshEarlyMs ?? 3e4;
|
|
70
|
+
const now = options.now ?? (() => Date.now());
|
|
71
|
+
let refreshing = null;
|
|
72
|
+
async function refresh(tokens) {
|
|
73
|
+
try {
|
|
74
|
+
const next = await post(fetcher, `${base}/api/v1/auth/refresh`, {
|
|
75
|
+
refreshToken: tokens.refreshToken
|
|
76
|
+
});
|
|
77
|
+
await options.store.save(next);
|
|
78
|
+
return next;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
if (error instanceof ApiError) await options.store.save(null);
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
/**
|
|
86
|
+
* Exchanges a sign-in for tokens. `credentials` are the headers that carry it, such as the
|
|
87
|
+
* cookie the sign-in answered with.
|
|
88
|
+
*/
|
|
89
|
+
async exchange(deviceName, credentials) {
|
|
90
|
+
const tokens = await post(fetcher, `${base}/api/v1/auth/token`, { deviceName }, credentials);
|
|
91
|
+
await options.store.save(tokens);
|
|
92
|
+
return tokens;
|
|
93
|
+
},
|
|
94
|
+
/**
|
|
95
|
+
* Asks the host to email a sign-in code (ADR 0455). The answer is the same whoever the
|
|
96
|
+
* address is; it throws only when the host refuses to send any (`rate_limited`, or sign-in
|
|
97
|
+
* not set up).
|
|
98
|
+
*/
|
|
99
|
+
async requestCode(email, audience = "customer") {
|
|
100
|
+
await post(fetcher, `${base}/api/v1/auth/${audience}/code`, { email });
|
|
101
|
+
},
|
|
102
|
+
/**
|
|
103
|
+
* Signs in with the emailed code and keeps the device session the host answers with. A wrong,
|
|
104
|
+
* used or expired code throws `forbidden` (`invalid_code`). No cookie is involved.
|
|
105
|
+
*/
|
|
106
|
+
async signInWithCode(email, code, deviceName, audience = "customer") {
|
|
107
|
+
const signedIn = await post(fetcher, `${base}/api/v1/auth/${audience}/sign-in`, {
|
|
108
|
+
email,
|
|
109
|
+
code,
|
|
110
|
+
deviceName
|
|
111
|
+
});
|
|
112
|
+
const { account: _account, ...tokens } = signedIn;
|
|
113
|
+
await options.store.save(tokens);
|
|
114
|
+
return signedIn;
|
|
115
|
+
},
|
|
116
|
+
/**
|
|
117
|
+
* Finishes a staff sign-in in the system browser (`startBrowserSignIn`): checks the state it
|
|
118
|
+
* was sent back with and exchanges the code, with the verifier, for a device session.
|
|
119
|
+
*/
|
|
120
|
+
async finishBrowserSignIn(input) {
|
|
121
|
+
const query = input.callbackUrl.includes("?") ? input.callbackUrl.split("?")[1] ?? "" : "";
|
|
122
|
+
const params = new Map(
|
|
123
|
+
query.split("&").filter(Boolean).map((pair) => {
|
|
124
|
+
const [key = "", value = ""] = pair.split("=");
|
|
125
|
+
return [decodeURIComponent(key), decodeURIComponent(value.replace(/\+/g, " "))];
|
|
126
|
+
})
|
|
127
|
+
);
|
|
128
|
+
const code = params.get("code");
|
|
129
|
+
if (!code || params.get("state") !== input.state) {
|
|
130
|
+
throw new ApiError(
|
|
131
|
+
"forbidden",
|
|
132
|
+
"The sign-in did not come back from this app's request",
|
|
133
|
+
401,
|
|
134
|
+
{
|
|
135
|
+
reason: "invalid_code"
|
|
136
|
+
}
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
const tokens = await post(fetcher, `${base}/api/v1/auth/staff/exchange`, {
|
|
140
|
+
code,
|
|
141
|
+
codeVerifier: input.verifier,
|
|
142
|
+
redirectUri: input.redirectUri,
|
|
143
|
+
deviceName: input.deviceName
|
|
144
|
+
});
|
|
145
|
+
await options.store.save(tokens);
|
|
146
|
+
return tokens;
|
|
147
|
+
},
|
|
148
|
+
/** The headers for a call: a current access token, refreshed first when it is about to end. */
|
|
149
|
+
async headers() {
|
|
150
|
+
let tokens = await options.store.load();
|
|
151
|
+
if (!tokens) return {};
|
|
152
|
+
if (Date.parse(tokens.accessExpiresAt) - early <= now()) {
|
|
153
|
+
refreshing ??= refresh(tokens).finally(() => {
|
|
154
|
+
refreshing = null;
|
|
155
|
+
});
|
|
156
|
+
tokens = await refreshing;
|
|
157
|
+
if (!tokens) return {};
|
|
158
|
+
}
|
|
159
|
+
return { authorization: `Bearer ${tokens.accessToken}` };
|
|
160
|
+
},
|
|
161
|
+
/**
|
|
162
|
+
* Ends this device's session on the host (ADR 0455) with its refresh token, which any account
|
|
163
|
+
* may do whatever it may call, then forgets the tokens, even when the host could not be
|
|
164
|
+
* reached.
|
|
165
|
+
*/
|
|
166
|
+
async signOut() {
|
|
167
|
+
const tokens = await options.store.load();
|
|
168
|
+
try {
|
|
169
|
+
if (tokens) {
|
|
170
|
+
await post(fetcher, `${base}/api/v1/auth/sign-out`, {
|
|
171
|
+
refreshToken: tokens.refreshToken
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
} catch {
|
|
175
|
+
} finally {
|
|
176
|
+
await options.store.save(null);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
function base64url(bytes) {
|
|
182
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
183
|
+
let out = "";
|
|
184
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
185
|
+
const a = bytes[i] ?? 0;
|
|
186
|
+
const b = bytes[i + 1];
|
|
187
|
+
const c = bytes[i + 2];
|
|
188
|
+
out += alphabet[a >> 2];
|
|
189
|
+
out += alphabet[(a & 3) << 4 | (b ?? 0) >> 4];
|
|
190
|
+
if (b !== void 0) out += alphabet[(b & 15) << 2 | (c ?? 0) >> 6];
|
|
191
|
+
if (c !== void 0) out += alphabet[c & 63];
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
async function startBrowserSignIn(options) {
|
|
196
|
+
const verifier = `${options.randomKey()}${options.randomKey()}`.replace(/[^A-Za-z0-9._~-]/g, "").slice(0, 128);
|
|
197
|
+
if (verifier.length < 43) throw new Error("randomKey must give at least 22 characters");
|
|
198
|
+
const state = options.randomKey().replace(/[^A-Za-z0-9._~-]/g, "");
|
|
199
|
+
const challenge = base64url(await options.sha256(verifier));
|
|
200
|
+
const query = [
|
|
201
|
+
["redirect_uri", options.redirectUri],
|
|
202
|
+
["code_challenge", challenge],
|
|
203
|
+
["code_challenge_method", "S256"],
|
|
204
|
+
["state", state]
|
|
205
|
+
].map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
|
|
206
|
+
return {
|
|
207
|
+
url: `${options.hostUrl.replace(/\/+$/, "")}/native/staff-sign-in?${query}`,
|
|
208
|
+
state,
|
|
209
|
+
verifier
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// src/content-import/format.ts
|
|
214
|
+
var POST_OBJECT = "content.post";
|
|
215
|
+
var CATEGORY_OBJECT = "content.category";
|
|
216
|
+
var STATUSES = ["draft", "scheduled", "published"];
|
|
217
|
+
var POST_FIELDS = {
|
|
218
|
+
key: "the post's import key (default: the file's name without .json)",
|
|
219
|
+
title: "text, required",
|
|
220
|
+
slug: "the address: lowercase words joined by hyphens (default: made from the title)",
|
|
221
|
+
excerpt: "text",
|
|
222
|
+
body: "rich text (RICH_TEXT_SCHEMA), a picture named by `file` where it has `media`",
|
|
223
|
+
cover: "{ file, alt, focal? }",
|
|
224
|
+
date: "ISO 8601 date and time: the date readers are shown, kept when published",
|
|
225
|
+
status: "draft | scheduled | published (default draft)",
|
|
226
|
+
category: "the category's name",
|
|
227
|
+
byline: "text: who wrote it, as readers see it",
|
|
228
|
+
seoTitle: "text",
|
|
229
|
+
seoDescription: "text",
|
|
230
|
+
seoImage: "{ file, alt, focal? }",
|
|
231
|
+
noindex: "true to ask search engines not to list it"
|
|
232
|
+
};
|
|
233
|
+
var PICTURE = "$picture";
|
|
234
|
+
var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
235
|
+
var DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
236
|
+
var KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
|
|
237
|
+
function withPictures(value, id) {
|
|
238
|
+
if (Array.isArray(value)) return value.map((v) => withPictures(v, id));
|
|
239
|
+
if (!isObject(value)) return value;
|
|
240
|
+
if (typeof value[PICTURE] === "string" && Object.keys(value).length === 1) {
|
|
241
|
+
return id(value[PICTURE]);
|
|
242
|
+
}
|
|
243
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, withPictures(v, id)]));
|
|
244
|
+
}
|
|
245
|
+
var placeholderMedia = (index) => `med_import${index}`;
|
|
246
|
+
function readFolder(files) {
|
|
247
|
+
const problems = [];
|
|
248
|
+
const posts = [];
|
|
249
|
+
const categories = /* @__PURE__ */ new Map();
|
|
250
|
+
const used = /* @__PURE__ */ new Map();
|
|
251
|
+
const keys = /* @__PURE__ */ new Map();
|
|
252
|
+
const slugs = /* @__PURE__ */ new Map();
|
|
253
|
+
const picturesProblems = /* @__PURE__ */ new Set();
|
|
254
|
+
for (const [file, text] of [...files.posts].sort(([a], [b]) => a.localeCompare(b))) {
|
|
255
|
+
const fault = (message) => problems.push({ file, message });
|
|
256
|
+
let raw;
|
|
257
|
+
try {
|
|
258
|
+
raw = JSON.parse(text);
|
|
259
|
+
} catch (error) {
|
|
260
|
+
fault(`Not JSON: ${error.message}`);
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
if (!isObject(raw)) {
|
|
264
|
+
fault("A post is a JSON object");
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
for (const name of Object.keys(raw)) {
|
|
268
|
+
if (!Object.hasOwn(POST_FIELDS, name)) {
|
|
269
|
+
fault(`Unknown field "${name}" (${Object.keys(POST_FIELDS).join(", ")})`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
const key = typeof raw.key === "string" ? raw.key : file.replace(/\.json$/i, "");
|
|
273
|
+
if (!KEY_RE.test(key)) fault(`The key "${key}" is not 1 to 200 letters, digits or ._:-`);
|
|
274
|
+
const other = keys.get(key);
|
|
275
|
+
if (other) fault(`The key "${key}" is ${other}'s too`);
|
|
276
|
+
keys.set(key, file);
|
|
277
|
+
const values = {};
|
|
278
|
+
const pictures = [];
|
|
279
|
+
const text_ = (name, max, required = false) => {
|
|
280
|
+
const v = raw[name];
|
|
281
|
+
if (v === void 0 || v === null) {
|
|
282
|
+
if (required) fault(`${name} is required`);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
if (typeof v !== "string" || required && !v.trim()) fault(`${name} is text`);
|
|
286
|
+
else if (v.length > max) fault(`${name} is at most ${max} characters`);
|
|
287
|
+
else values[name] = v;
|
|
288
|
+
};
|
|
289
|
+
text_("title", 1e3, true);
|
|
290
|
+
text_("excerpt", 1e3);
|
|
291
|
+
text_("byline", 1e3);
|
|
292
|
+
text_("seoTitle", 1e3);
|
|
293
|
+
text_("seoDescription", 1e3);
|
|
294
|
+
if (raw.slug !== void 0) {
|
|
295
|
+
if (typeof raw.slug !== "string" || raw.slug.length > SLUG_MAX || !SLUG_RE.test(raw.slug)) {
|
|
296
|
+
fault("slug is lowercase letters and digits in words joined by hyphens");
|
|
297
|
+
} else {
|
|
298
|
+
values.slug = raw.slug;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const slug = values.slug ?? slugify(String(raw.title ?? ""));
|
|
302
|
+
if (slug) {
|
|
303
|
+
const holder = slugs.get(slug);
|
|
304
|
+
if (holder) fault(`The address "${slug}" is ${holder}'s too`);
|
|
305
|
+
slugs.set(slug, file);
|
|
306
|
+
}
|
|
307
|
+
const picture = (given, path) => {
|
|
308
|
+
if (typeof given !== "string" || !given || given.includes("/") || given.includes("\\")) {
|
|
309
|
+
fault(`${path}: a picture is a file name in pictures/`);
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
const bytes = files.pictures.get(given);
|
|
313
|
+
if (!bytes) {
|
|
314
|
+
fault(`${path}: pictures/${given} is not there`);
|
|
315
|
+
return null;
|
|
316
|
+
}
|
|
317
|
+
const problem = mediaProblem(bytes);
|
|
318
|
+
if (problem) {
|
|
319
|
+
if (!picturesProblems.has(given))
|
|
320
|
+
problems.push({ file: `pictures/${given}`, message: problem });
|
|
321
|
+
picturesProblems.add(given);
|
|
322
|
+
fault(`${path}: pictures/${given} cannot be uploaded`);
|
|
323
|
+
return null;
|
|
324
|
+
}
|
|
325
|
+
used.set(given, bytes);
|
|
326
|
+
pictures.push(given);
|
|
327
|
+
return { [PICTURE]: given };
|
|
328
|
+
};
|
|
329
|
+
for (const name of ["cover", "seoImage"]) {
|
|
330
|
+
const v = raw[name];
|
|
331
|
+
if (v === void 0 || v === null) continue;
|
|
332
|
+
if (!isObject(v)) {
|
|
333
|
+
fault(`${name} is { file, alt, focal? }`);
|
|
334
|
+
continue;
|
|
335
|
+
}
|
|
336
|
+
const { file: pictureFile, ...rest } = v;
|
|
337
|
+
const ref = picture(pictureFile, name);
|
|
338
|
+
const candidate = { media: placeholderMedia(0), ...rest };
|
|
339
|
+
const checked = validateDocument(IMAGE_SCHEMA, candidate);
|
|
340
|
+
if (!checked.ok) {
|
|
341
|
+
for (const issue of checked.issues) {
|
|
342
|
+
fault(`${name}.${issue.path.join(".")}: ${issue.message}`);
|
|
343
|
+
}
|
|
344
|
+
continue;
|
|
345
|
+
}
|
|
346
|
+
if (ref) values[name] = { ...rest, media: ref };
|
|
347
|
+
}
|
|
348
|
+
if (raw.body !== void 0 && raw.body !== null) {
|
|
349
|
+
let n = 0;
|
|
350
|
+
const placed = JSON.parse(JSON.stringify(raw.body), function(_k, v) {
|
|
351
|
+
if (isObject(v) && v.type === "image" && typeof v.file === "string" && !("media" in v)) {
|
|
352
|
+
const { file: f, ...rest } = v;
|
|
353
|
+
const ref = picture(f, `body (picture ${f})`);
|
|
354
|
+
n += 1;
|
|
355
|
+
return { ...rest, media: ref ?? placeholderMedia(n) };
|
|
356
|
+
}
|
|
357
|
+
return v;
|
|
358
|
+
});
|
|
359
|
+
const check = withPictures(placed, () => placeholderMedia(0));
|
|
360
|
+
const checked = validateDocument(RICH_TEXT_SCHEMA, check, { maxBytes: 524288 });
|
|
361
|
+
if (!checked.ok) {
|
|
362
|
+
for (const issue of checked.issues) {
|
|
363
|
+
fault(`body.${issue.path.join(".")}: ${issue.message}`);
|
|
364
|
+
}
|
|
365
|
+
} else {
|
|
366
|
+
values.body = placed;
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
let date = null;
|
|
370
|
+
if (raw.date !== void 0 && raw.date !== null) {
|
|
371
|
+
if (typeof raw.date !== "string" || !DATETIME_RE.test(raw.date) || Number.isNaN(Date.parse(raw.date))) {
|
|
372
|
+
fault("date is an ISO 8601 date and time, with its zone (2024-05-01T09:00:00Z)");
|
|
373
|
+
} else {
|
|
374
|
+
date = new Date(raw.date).toISOString();
|
|
375
|
+
values.date = date;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const status = raw.status ?? "draft";
|
|
379
|
+
if (!STATUSES.includes(status)) fault(`status is one of ${STATUSES.join(", ")}`);
|
|
380
|
+
if (status === "scheduled" && !date) fault("A scheduled post has the date it goes live");
|
|
381
|
+
if (raw.noindex !== void 0) {
|
|
382
|
+
if (typeof raw.noindex !== "boolean") fault("noindex is true or false");
|
|
383
|
+
else values.noindex = raw.noindex;
|
|
384
|
+
}
|
|
385
|
+
let category = null;
|
|
386
|
+
if (raw.category !== void 0 && raw.category !== null) {
|
|
387
|
+
const name = typeof raw.category === "string" ? raw.category.trim() : "";
|
|
388
|
+
const categorySlug = slugify(name);
|
|
389
|
+
if (!name || !categorySlug || name.length > 1e3) fault("category is the category's name");
|
|
390
|
+
else {
|
|
391
|
+
category = `category:${categorySlug}`;
|
|
392
|
+
if (!categories.has(category)) {
|
|
393
|
+
categories.set(category, { key: category, values: { name, slug: categorySlug } });
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
posts.push({ file, key, status, date, values, category, pictures });
|
|
398
|
+
}
|
|
399
|
+
return { posts, categories: [...categories.values()], pictures: used, problems };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// src/content-import/engine.ts
|
|
403
|
+
var BATCH = 25;
|
|
404
|
+
var chunks = (list, size) => Array.from(
|
|
405
|
+
{ length: Math.ceil(list.length / size) },
|
|
406
|
+
(_, i) => list.slice(i * size, (i + 1) * size)
|
|
407
|
+
);
|
|
408
|
+
async function sha256(bytes) {
|
|
409
|
+
const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
|
|
410
|
+
return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
411
|
+
}
|
|
412
|
+
function resolved(post2, media, category) {
|
|
413
|
+
const values = withPictures(post2.values, media);
|
|
414
|
+
if (post2.category) {
|
|
415
|
+
const id = category(post2.category);
|
|
416
|
+
if (id) values.category = id;
|
|
417
|
+
}
|
|
418
|
+
return values;
|
|
419
|
+
}
|
|
420
|
+
async function importRecords(host, object, records, options) {
|
|
421
|
+
const out = [];
|
|
422
|
+
for (const part of chunks(records, BATCH)) {
|
|
423
|
+
const answer = await host.call("record.import", {
|
|
424
|
+
object,
|
|
425
|
+
records: part.map(({ key, values }) => ({ key, values })),
|
|
426
|
+
dryRun: options.dryRun,
|
|
427
|
+
checkReferences: options.checkReferences
|
|
428
|
+
});
|
|
429
|
+
for (const result of answer.results) {
|
|
430
|
+
const file = part.find((r) => r.key === result.key)?.file ?? null;
|
|
431
|
+
out.push({ ...result, object, file });
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return out;
|
|
435
|
+
}
|
|
436
|
+
async function unpublishedNote(host, post2, result) {
|
|
437
|
+
if (result?.id && (result.outcome === "unchanged" || result.outcome === "updated")) {
|
|
438
|
+
const record = await host.call("record.get", {
|
|
439
|
+
object: POST_OBJECT,
|
|
440
|
+
id: result.id
|
|
441
|
+
});
|
|
442
|
+
const state = record.values.publishState;
|
|
443
|
+
const same = post2.status === "published" ? state === "published" : state === "scheduled" && record.values.publishAt === post2.date;
|
|
444
|
+
if (same) {
|
|
445
|
+
return result.outcome === "unchanged" ? null : post2.status === "published" ? "Published here already: the change is saved, not published (pass --publish to publish it)" : "Scheduled here already: the change is saved, not published (pass --publish to schedule it)";
|
|
446
|
+
}
|
|
447
|
+
if (state === "published" || state === "scheduled") {
|
|
448
|
+
return "Already " + state + " here; left as it is (pass --publish to publish or schedule it as the source has it)";
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
return post2.status === "scheduled" ? `Scheduled for ${post2.date} in the source: imported as a draft (pass --publish to schedule it)` : "Published in the source: imported as a draft (pass --publish to publish it)";
|
|
452
|
+
}
|
|
453
|
+
async function runImport(plan, host, options = {}) {
|
|
454
|
+
const report = {
|
|
455
|
+
problems: [...plan.problems],
|
|
456
|
+
records: [],
|
|
457
|
+
pictures: { uploaded: 0, already: 0 },
|
|
458
|
+
published: [],
|
|
459
|
+
notes: [],
|
|
460
|
+
wroteNothing: true
|
|
461
|
+
};
|
|
462
|
+
if (report.problems.length) return report;
|
|
463
|
+
const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
464
|
+
const hashes = /* @__PURE__ */ new Map();
|
|
465
|
+
for (const [file, bytes] of plan.pictures) hashes.set(file, await sha256(bytes));
|
|
466
|
+
const known = /* @__PURE__ */ new Map();
|
|
467
|
+
for (const part of chunks([...new Set(hashes.values())], 200)) {
|
|
468
|
+
if (!part.length) continue;
|
|
469
|
+
const found = await host.call("media.findByHash", {
|
|
470
|
+
sha256: part
|
|
471
|
+
});
|
|
472
|
+
for (const item of found.items) known.set(item.sha256, item.id);
|
|
473
|
+
}
|
|
474
|
+
const dryCategories = await importRecords(
|
|
475
|
+
host,
|
|
476
|
+
CATEGORY_OBJECT,
|
|
477
|
+
plan.categories.map((c) => ({ key: c.key, file: null, values: c.values })),
|
|
478
|
+
{ dryRun: true, checkReferences: false }
|
|
479
|
+
);
|
|
480
|
+
const placeholders = new Map(
|
|
481
|
+
[...plan.pictures.keys()].map((f, i) => [
|
|
482
|
+
f,
|
|
483
|
+
known.get(hashes.get(f)) ?? placeholderMedia(i)
|
|
484
|
+
])
|
|
485
|
+
);
|
|
486
|
+
const dryCategoryIds = new Map(dryCategories.map((c) => [c.key, c.id]));
|
|
487
|
+
const dryPosts = await importRecords(
|
|
488
|
+
host,
|
|
489
|
+
POST_OBJECT,
|
|
490
|
+
plan.posts.map((post2) => ({
|
|
491
|
+
key: post2.key,
|
|
492
|
+
file: post2.file,
|
|
493
|
+
values: resolved(
|
|
494
|
+
post2,
|
|
495
|
+
(f) => placeholders.get(f) ?? placeholderMedia(0),
|
|
496
|
+
(key) => dryCategoryIds.get(key) ?? "rec_importplaceholder"
|
|
497
|
+
)
|
|
498
|
+
})),
|
|
499
|
+
{ dryRun: true, checkReferences: false }
|
|
500
|
+
);
|
|
501
|
+
for (const result of [...dryCategories, ...dryPosts]) {
|
|
502
|
+
if (result.outcome === "invalid") {
|
|
503
|
+
for (const message of result.problems) {
|
|
504
|
+
report.problems.push({ file: result.file ?? `category ${result.key}`, message });
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
for (const post2 of plan.posts) {
|
|
509
|
+
if (post2.status === "draft" || options.publish) continue;
|
|
510
|
+
const note = await unpublishedNote(
|
|
511
|
+
host,
|
|
512
|
+
post2,
|
|
513
|
+
dryPosts.find((r) => r.key === post2.key)
|
|
514
|
+
);
|
|
515
|
+
if (note) report.notes.push({ file: post2.file, message: note });
|
|
516
|
+
}
|
|
517
|
+
if (report.problems.length || options.dryRun) {
|
|
518
|
+
report.records = [...dryCategories, ...dryPosts];
|
|
519
|
+
return report;
|
|
520
|
+
}
|
|
521
|
+
if (options.publish && options.confirm) {
|
|
522
|
+
const live = plan.posts.filter((p) => p.status !== "draft");
|
|
523
|
+
const summary = `Publish ${live.filter((p) => p.status === "published").length} post(s) and schedule ${live.filter((p) => p.status === "scheduled").length}, as you, with their own dates`;
|
|
524
|
+
if (!await options.confirm(summary)) {
|
|
525
|
+
report.notes.push({ file: "", message: "Stopped before writing: not confirmed" });
|
|
526
|
+
return report;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
const ids = /* @__PURE__ */ new Map();
|
|
530
|
+
for (const [file, bytes] of plan.pictures) {
|
|
531
|
+
const hash = hashes.get(file);
|
|
532
|
+
let id = known.get(hash);
|
|
533
|
+
if (id) report.pictures.already += 1;
|
|
534
|
+
else {
|
|
535
|
+
report.wroteNothing = false;
|
|
536
|
+
const uploaded = await host.upload(bytes, file);
|
|
537
|
+
id = uploaded.id;
|
|
538
|
+
known.set(hash, id);
|
|
539
|
+
if (uploaded.existing) report.pictures.already += 1;
|
|
540
|
+
else report.pictures.uploaded += 1;
|
|
541
|
+
}
|
|
542
|
+
ids.set(file, id);
|
|
543
|
+
}
|
|
544
|
+
const categories = await importRecords(
|
|
545
|
+
host,
|
|
546
|
+
CATEGORY_OBJECT,
|
|
547
|
+
plan.categories.map((c) => ({ key: c.key, file: null, values: c.values })),
|
|
548
|
+
{ dryRun: false, checkReferences: true }
|
|
549
|
+
);
|
|
550
|
+
const categoryIds = new Map(categories.map((c) => [c.key, c.id]));
|
|
551
|
+
const posts = await importRecords(
|
|
552
|
+
host,
|
|
553
|
+
POST_OBJECT,
|
|
554
|
+
plan.posts.map((post2) => ({
|
|
555
|
+
key: post2.key,
|
|
556
|
+
file: post2.file,
|
|
557
|
+
values: resolved(
|
|
558
|
+
post2,
|
|
559
|
+
(f) => ids.get(f),
|
|
560
|
+
(key) => categoryIds.get(key) ?? null
|
|
561
|
+
)
|
|
562
|
+
})),
|
|
563
|
+
{ dryRun: false, checkReferences: true }
|
|
564
|
+
);
|
|
565
|
+
report.records = [...categories, ...posts];
|
|
566
|
+
if (report.records.some((r) => r.outcome === "created" || r.outcome === "updated")) {
|
|
567
|
+
report.wroteNothing = false;
|
|
568
|
+
}
|
|
569
|
+
if (options.publish) {
|
|
570
|
+
for (const post2 of plan.posts) {
|
|
571
|
+
const result = posts.find((r) => r.key === post2.key);
|
|
572
|
+
if (!result?.id || result.outcome === "conflict" || result.outcome === "invalid") continue;
|
|
573
|
+
if (post2.status === "draft") continue;
|
|
574
|
+
const id = result.id;
|
|
575
|
+
const record = await host.call("record.get", {
|
|
576
|
+
object: POST_OBJECT,
|
|
577
|
+
id
|
|
578
|
+
});
|
|
579
|
+
const state = record.values.publishState;
|
|
580
|
+
const due = post2.status === "scheduled" && post2.date && Date.parse(post2.date) > now.getTime();
|
|
581
|
+
if (due) {
|
|
582
|
+
if (state === "scheduled" && record.values.publishAt === post2.date) {
|
|
583
|
+
report.published.push({ file: post2.file, id, as: "unchanged" });
|
|
584
|
+
continue;
|
|
585
|
+
}
|
|
586
|
+
await host.call("record.schedulePublish", {
|
|
587
|
+
object: POST_OBJECT,
|
|
588
|
+
id,
|
|
589
|
+
at: post2.date,
|
|
590
|
+
note: "Imported"
|
|
591
|
+
});
|
|
592
|
+
report.wroteNothing = false;
|
|
593
|
+
report.published.push({ file: post2.file, id, as: "scheduled" });
|
|
594
|
+
continue;
|
|
595
|
+
}
|
|
596
|
+
if (post2.status === "scheduled") {
|
|
597
|
+
report.notes.push({
|
|
598
|
+
file: post2.file,
|
|
599
|
+
message: `Scheduled for ${post2.date}, which has passed: published`
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
if (state === "published" && typeof record.values.publishedVersion === "number") {
|
|
603
|
+
const diff = await host.call("record.compareVersions", {
|
|
604
|
+
object: POST_OBJECT,
|
|
605
|
+
id,
|
|
606
|
+
from: record.values.publishedVersion
|
|
607
|
+
});
|
|
608
|
+
if (!diff.changes.length) {
|
|
609
|
+
report.published.push({ file: post2.file, id, as: "unchanged" });
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
await host.call("record.publish", { object: POST_OBJECT, id, note: "Imported" });
|
|
614
|
+
report.wroteNothing = false;
|
|
615
|
+
report.published.push({ file: post2.file, id, as: "published" });
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
return report;
|
|
619
|
+
}
|
|
620
|
+
function reportLines(report, dryRun) {
|
|
621
|
+
const lines = [];
|
|
622
|
+
if (report.problems.length) {
|
|
623
|
+
lines.push(`Nothing was written: ${report.problems.length} problem(s).`);
|
|
624
|
+
for (const p of report.problems) lines.push(` ${p.file}: ${p.message}`);
|
|
625
|
+
return lines;
|
|
626
|
+
}
|
|
627
|
+
const by = (outcome) => report.records.filter((r) => r.outcome === outcome);
|
|
628
|
+
const verb = dryRun ? "would be" : "were";
|
|
629
|
+
for (const [outcome, label] of [
|
|
630
|
+
["created", "created"],
|
|
631
|
+
["updated", "updated"],
|
|
632
|
+
["unchanged", "unchanged"]
|
|
633
|
+
]) {
|
|
634
|
+
const list = by(outcome);
|
|
635
|
+
if (list.length)
|
|
636
|
+
lines.push(`${list.length} record(s) ${outcome === "unchanged" ? "are" : verb} ${label}.`);
|
|
637
|
+
}
|
|
638
|
+
const conflicts = by("conflict");
|
|
639
|
+
if (conflicts.length) {
|
|
640
|
+
lines.push(`${conflicts.length} conflict(s), left as they are:`);
|
|
641
|
+
for (const c of conflicts) lines.push(` ${c.file ?? c.key}: ${c.problems.join("; ")}`);
|
|
642
|
+
}
|
|
643
|
+
if (!dryRun) {
|
|
644
|
+
lines.push(
|
|
645
|
+
`Pictures: ${report.pictures.uploaded} uploaded, ${report.pictures.already} already in the library.`
|
|
646
|
+
);
|
|
647
|
+
}
|
|
648
|
+
for (const p of report.published) {
|
|
649
|
+
if (p.as !== "unchanged") lines.push(` ${p.file}: ${p.as}`);
|
|
650
|
+
}
|
|
651
|
+
for (const note of report.notes)
|
|
652
|
+
lines.push(` ${note.file ? `${note.file}: ` : ""}${note.message}`);
|
|
653
|
+
return lines;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// src/content-import/host.ts
|
|
657
|
+
function sessionHost(base, headers, fetcher = fetch) {
|
|
658
|
+
return {
|
|
659
|
+
async call(name, input) {
|
|
660
|
+
const response = await fetcher(`${base}/api/v1/op/${encodeURIComponent(name)}`, {
|
|
661
|
+
method: "POST",
|
|
662
|
+
headers: {
|
|
663
|
+
"content-type": "application/json",
|
|
664
|
+
"idempotency-key": crypto.randomUUID(),
|
|
665
|
+
...await headers()
|
|
666
|
+
},
|
|
667
|
+
body: JSON.stringify(input)
|
|
668
|
+
});
|
|
669
|
+
const body = await response.json();
|
|
670
|
+
if (!response.ok || body.error) {
|
|
671
|
+
throw Object.assign(new Error(body.error?.message ?? `${name}: HTTP ${response.status}`), {
|
|
672
|
+
code: body.error?.code,
|
|
673
|
+
details: body.error?.details
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
return body.data;
|
|
677
|
+
},
|
|
678
|
+
async upload(bytes, name) {
|
|
679
|
+
const response = await fetcher(`${base}/api/v1/media?${new URLSearchParams({ name })}`, {
|
|
680
|
+
method: "POST",
|
|
681
|
+
headers: { "content-type": "application/octet-stream", ...await headers() },
|
|
682
|
+
body: new Uint8Array(bytes)
|
|
683
|
+
});
|
|
684
|
+
const body = await response.json();
|
|
685
|
+
if (!response.ok || !body.data) {
|
|
686
|
+
throw new Error(`pictures/${name}: ${body.error?.message ?? `HTTP ${response.status}`}`);
|
|
687
|
+
}
|
|
688
|
+
return body.data;
|
|
689
|
+
}
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// src/content-import/run.ts
|
|
694
|
+
var LOOPBACK_PATH = "/cos-sign-in";
|
|
695
|
+
function readImportFolder(dir) {
|
|
696
|
+
const root = resolve(dir);
|
|
697
|
+
if (!existsSync(root) || !statSync(root).isDirectory()) {
|
|
698
|
+
throw new Error(`${dir} is not a folder`);
|
|
699
|
+
}
|
|
700
|
+
const posts = /* @__PURE__ */ new Map();
|
|
701
|
+
for (const name of readdirSync(root)) {
|
|
702
|
+
if (name.toLowerCase().endsWith(".json"))
|
|
703
|
+
posts.set(name, readFileSync(join(root, name), "utf8"));
|
|
704
|
+
}
|
|
705
|
+
const pictures = /* @__PURE__ */ new Map();
|
|
706
|
+
const folder = join(root, "pictures");
|
|
707
|
+
if (existsSync(folder)) {
|
|
708
|
+
for (const name of readdirSync(folder)) {
|
|
709
|
+
const path = join(folder, name);
|
|
710
|
+
if (statSync(path).isFile()) pictures.set(name, new Uint8Array(readFileSync(path)));
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return { posts, pictures };
|
|
714
|
+
}
|
|
715
|
+
function memoryStore() {
|
|
716
|
+
let saved = null;
|
|
717
|
+
return {
|
|
718
|
+
load: async () => saved,
|
|
719
|
+
save: async (tokens) => {
|
|
720
|
+
saved = tokens;
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
var hex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
725
|
+
function openBrowser(url, io) {
|
|
726
|
+
io.out(`Sign in in your browser: ${url}`);
|
|
727
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
|
|
728
|
+
execFile(command, [url], () => {
|
|
729
|
+
});
|
|
730
|
+
}
|
|
731
|
+
async function loopback() {
|
|
732
|
+
let settle;
|
|
733
|
+
const callback = new Promise((resolve_) => {
|
|
734
|
+
settle = resolve_;
|
|
735
|
+
});
|
|
736
|
+
const server = createServer((req, res) => {
|
|
737
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
738
|
+
if (url.pathname !== LOOPBACK_PATH) {
|
|
739
|
+
res.writeHead(404).end();
|
|
740
|
+
return;
|
|
741
|
+
}
|
|
742
|
+
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end("Signed in. You can close this tab and go back to the terminal.");
|
|
743
|
+
settle(`http://127.0.0.1${req.url}`);
|
|
744
|
+
});
|
|
745
|
+
await new Promise((done) => server.listen(0, "127.0.0.1", done));
|
|
746
|
+
const port = server.address().port;
|
|
747
|
+
return {
|
|
748
|
+
redirectUri: `http://127.0.0.1:${port}${LOOPBACK_PATH}`,
|
|
749
|
+
callback,
|
|
750
|
+
close: () => server.close()
|
|
751
|
+
};
|
|
752
|
+
}
|
|
753
|
+
async function contentImport(positional, flags, io) {
|
|
754
|
+
const dir = positional[0];
|
|
755
|
+
if (!dir) {
|
|
756
|
+
io.err(
|
|
757
|
+
`Usage: cos content import <folder> --host <https://host> [--email <you>] [--dry-run] [--publish] [--yes]
|
|
758
|
+
|
|
759
|
+
A post file's fields: ${Object.entries(
|
|
760
|
+
POST_FIELDS
|
|
761
|
+
).map(([k, v]) => `${k} (${v})`).join("; ")}. See docs/importing.md.`
|
|
762
|
+
);
|
|
763
|
+
return 2;
|
|
764
|
+
}
|
|
765
|
+
const host = flags.host?.replace(/\/+$/, "");
|
|
766
|
+
if (!host || !/^https?:\/\//.test(host)) {
|
|
767
|
+
io.err("--host is the host's address, e.g. https://admin.example.com");
|
|
768
|
+
return 2;
|
|
769
|
+
}
|
|
770
|
+
const plan = readFolder(readImportFolder(dir));
|
|
771
|
+
if (plan.problems.length) {
|
|
772
|
+
io.err(`Nothing was written: ${plan.problems.length} problem(s) in ${dir}.`);
|
|
773
|
+
for (const p of plan.problems) io.err(` ${p.file}: ${p.message}`);
|
|
774
|
+
return 1;
|
|
775
|
+
}
|
|
776
|
+
io.out(
|
|
777
|
+
`${plan.posts.length} post(s), ${plan.categories.length} categor${plan.categories.length === 1 ? "y" : "ies"} and ${plan.pictures.size} picture(s) in ${dir}.`
|
|
778
|
+
);
|
|
779
|
+
const store = memoryStore();
|
|
780
|
+
const session = tokenSession({ baseUrl: host, store });
|
|
781
|
+
const deviceName = `cos content import on ${hostname()}`.slice(0, 100);
|
|
782
|
+
try {
|
|
783
|
+
if (flags.email) {
|
|
784
|
+
await session.requestCode(flags.email, "staff");
|
|
785
|
+
io.out(
|
|
786
|
+
`If ${flags.email} may sign in by code, a code is on its way. If none arrives in a minute or two, check on the host: the address is one an admin invited, or one you confirmed (your account menu, Confirm your email), and Settings \u2192 Users shows sign-in codes going out (Send sign-in codes without review). Or run without --email to sign in with the browser.`
|
|
787
|
+
);
|
|
788
|
+
const code = await io.ask(`The sign-in code sent to ${flags.email}`, { secret: true });
|
|
789
|
+
await session.signInWithCode(flags.email, code.trim(), deviceName, "staff");
|
|
790
|
+
} else {
|
|
791
|
+
const back = await loopback();
|
|
792
|
+
try {
|
|
793
|
+
const random = () => hex(crypto.getRandomValues(new Uint8Array(16)));
|
|
794
|
+
const started = await startBrowserSignIn({
|
|
795
|
+
hostUrl: host,
|
|
796
|
+
redirectUri: back.redirectUri,
|
|
797
|
+
randomKey: random,
|
|
798
|
+
sha256: async (text) => new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))
|
|
799
|
+
});
|
|
800
|
+
openBrowser(started.url, io);
|
|
801
|
+
const callbackUrl = await back.callback;
|
|
802
|
+
await session.finishBrowserSignIn({
|
|
803
|
+
callbackUrl,
|
|
804
|
+
state: started.state,
|
|
805
|
+
verifier: started.verifier,
|
|
806
|
+
redirectUri: back.redirectUri,
|
|
807
|
+
deviceName
|
|
808
|
+
});
|
|
809
|
+
} finally {
|
|
810
|
+
back.close();
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
} catch (error) {
|
|
814
|
+
io.err(`Could not sign in: ${error.message}`);
|
|
815
|
+
return 1;
|
|
816
|
+
}
|
|
817
|
+
try {
|
|
818
|
+
const report = await runImport(
|
|
819
|
+
plan,
|
|
820
|
+
sessionHost(host, () => session.headers()),
|
|
821
|
+
{
|
|
822
|
+
dryRun: Boolean(flags.dryRun),
|
|
823
|
+
publish: Boolean(flags.publish),
|
|
824
|
+
confirm: async (summary) => {
|
|
825
|
+
if (flags.yes) return true;
|
|
826
|
+
if (!io.interactive) {
|
|
827
|
+
io.err(`${summary}. Pass --yes to confirm it when running from a script.`);
|
|
828
|
+
return false;
|
|
829
|
+
}
|
|
830
|
+
const answer = await io.ask(`${summary}. Go ahead? (yes/no)`, { default: "no" });
|
|
831
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
);
|
|
835
|
+
for (const line of reportLines(report, Boolean(flags.dryRun))) {
|
|
836
|
+
(report.problems.length ? io.err : io.out)(line);
|
|
837
|
+
}
|
|
838
|
+
return report.problems.length ? 1 : 0;
|
|
839
|
+
} finally {
|
|
840
|
+
await session.signOut();
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
export {
|
|
844
|
+
LOOPBACK_PATH,
|
|
845
|
+
contentImport,
|
|
846
|
+
readImportFolder
|
|
847
|
+
};
|