linopress-cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,42 @@
1
+ /**
2
+ * A single Markdown page produced by a source (for TypeDoc: one module).
3
+ * Its `path` is its identity across runs, so keep it stable.
4
+ */
5
+ interface Page {
6
+ /** POSIX path relative to the edition root, e.g. `client.md` or `internal/retry.md`. */
7
+ readonly path: string;
8
+ /** Human title, without any edition prefix. */
9
+ readonly title: string;
10
+ /** Markdown body. Relative `.md` links are rewritten to document URLs at sync time. */
11
+ readonly content: string;
12
+ /** Absolute paths of the source files the page documents (for TypeDoc: the module's file). */
13
+ readonly sources?: readonly string[];
14
+ }
15
+ /** Where documents live in the target. Linear accepts both teams and projects. */
16
+ type Container = {
17
+ readonly type: "team";
18
+ readonly id: string;
19
+ } | {
20
+ readonly type: "project";
21
+ readonly id: string;
22
+ };
23
+ /** How pages are arranged in the target. */
24
+ type LayoutMode = "nested" | "flat";
25
+ /**
26
+ * A page placed in the target's tree: the unit the engine plans and applies.
27
+ * `parentPath` points at another node's `path` (or `null` for a top-level doc).
28
+ */
29
+ interface DocNode {
30
+ readonly path: string;
31
+ readonly title: string;
32
+ readonly content: string;
33
+ readonly parentPath: string | null;
34
+ readonly sortOrder: number;
35
+ /** The page's source files, if the source knows them. Used by footers, never hashed. */
36
+ readonly sources?: readonly string[];
37
+ }
38
+ /** Stable string key for a container, used to scope the manifest. */
39
+ declare function containerKey(container: Container): string;
40
+ /** Parses `team:<id>` / `project:<id>`. */
41
+ declare function parseContainerKey(key: string): Container;
42
+ export { containerKey as a, Page as i, DocNode as n, parseContainerKey as o, LayoutMode as r, Container as t };
@@ -0,0 +1,185 @@
1
+ import { posix } from "node:path";
2
+ // ../core/src/format.ts
3
+ const SYMBOL = {
4
+ create: "+",
5
+ update: "~",
6
+ move: ">",
7
+ archive: "-",
8
+ unchanged: "="
9
+ };
10
+ function where(parentPath, sortOrder) {
11
+ return `${parentPath ?? "(top level)"} #${sortOrder}`;
12
+ }
13
+ function detail(action) {
14
+ switch (action.kind) {
15
+ case "create": return `under ${where(action.parentPath, action.sortOrder)}`;
16
+ case "update":
17
+ case "move": {
18
+ const parts = [];
19
+ if (action.changes.includes("content")) parts.push("content");
20
+ if (action.changes.includes("title")) parts.push(`title "${action.from.title}"`);
21
+ if (action.changes.includes("parent") || action.changes.includes("order")) parts.push(`${where(action.from.parentPath, action.from.sortOrder)} → ${where(action.parentPath, action.sortOrder)}`);
22
+ return parts.join(", ");
23
+ }
24
+ case "archive":
25
+ case "unchanged": return action.url;
26
+ }
27
+ }
28
+ /** Human-readable plan, one line per action, terraform-style. */
29
+ function formatPlan(p, options = {}) {
30
+ const { create, update, move, archive, unchanged } = p.counts;
31
+ const lines = [`${create} to create, ${update} to update, ${move} to move, ${archive} to archive, ${unchanged} unchanged`];
32
+ const shown = p.actions.filter((a) => options.verbose || a.kind !== "unchanged");
33
+ if (shown.length > 0) lines.push("");
34
+ const titleWidth = Math.max(0, ...shown.map((a) => a.title.length));
35
+ const pathWidth = Math.max(0, ...shown.map((a) => a.path.length + 2));
36
+ for (const a of shown) {
37
+ const title = a.title.padEnd(titleWidth);
38
+ const path = `(${a.path})`.padEnd(pathWidth);
39
+ lines.push(` ${SYMBOL[a.kind]} ${a.kind.padEnd(9)} ${title} ${path} ${detail(a)}`);
40
+ }
41
+ if (p.uploads.length > 0) {
42
+ lines.push("", `Images to upload (${p.uploads.length}):`);
43
+ for (const path of p.uploads) lines.push(` ↑ ${path}`);
44
+ }
45
+ const unresolved = Object.entries(p.unresolvedLinks);
46
+ if (unresolved.length > 0) {
47
+ lines.push("", "Unresolved links (left as-is):");
48
+ for (const [path, targets] of unresolved) lines.push(` ${path} → ${targets.join(", ")}`);
49
+ }
50
+ const missing = Object.entries(p.missingImages);
51
+ if (missing.length > 0) {
52
+ lines.push("", "Missing images and files (left as-is):");
53
+ for (const [path, images] of missing) lines.push(` ${path} → ${images.join(", ")}`);
54
+ }
55
+ return lines.join("\n");
56
+ }
57
+ // ../core/src/layout.ts
58
+ /** Placeholder index body used when the source has no index page. */
59
+ function synthesizeIndex(path, pages) {
60
+ const dir = posix.dirname(path);
61
+ const href = (target) => encodeURI(posix.relative(dir, target)).replace(/[()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
62
+ const items = pages.map((p) => `- [${p.title}](${href(p.path)})`).join("\n");
63
+ return {
64
+ path,
65
+ title: "Index",
66
+ content: items ? `${items}\n` : "_No pages._\n"
67
+ };
68
+ }
69
+ /**
70
+ * Places pages in the target's tree.
71
+ *
72
+ * - **nested** (default): the index doc is the root; every other page is its child.
73
+ * - **flat**: every doc is top-level; titles get a `rootTitle · ` prefix so they group together.
74
+ *
75
+ * Order is deterministic: the index first, then pages by path.
76
+ */
77
+ function layoutPages(pages, options) {
78
+ const indexPath = options.indexPath ?? "README.md";
79
+ const separator = options.separator ?? " · ";
80
+ const seen = /* @__PURE__ */ new Set();
81
+ for (const page of pages) {
82
+ if (seen.has(page.path)) throw new Error(`Duplicate page path "${page.path}"`);
83
+ seen.add(page.path);
84
+ }
85
+ const children = pages.filter((p) => p.path !== indexPath).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
86
+ const index = pages.find((p) => p.path === indexPath) ?? synthesizeIndex(indexPath, children);
87
+ return [{
88
+ path: index.path,
89
+ title: options.rootTitle,
90
+ content: index.content,
91
+ parentPath: null,
92
+ sortOrder: 0,
93
+ ...index.sources && { sources: index.sources }
94
+ }, ...children.map((page, i) => {
95
+ const sortOrder = i + 1;
96
+ return options.mode === "nested" ? {
97
+ path: page.path,
98
+ title: page.title,
99
+ content: page.content,
100
+ parentPath: index.path,
101
+ sortOrder,
102
+ ...page.sources && { sources: page.sources }
103
+ } : {
104
+ path: page.path,
105
+ title: `${options.rootTitle}${separator}${page.title}`,
106
+ content: page.content,
107
+ parentPath: null,
108
+ sortOrder,
109
+ ...page.sources && { sources: page.sources }
110
+ };
111
+ })];
112
+ }
113
+ // ../core/src/manifest.ts
114
+ function emptyManifest() {
115
+ return {
116
+ version: 1,
117
+ containers: {},
118
+ assets: {}
119
+ };
120
+ }
121
+ function isRecord(value) {
122
+ return typeof value === "object" && value !== null && !Array.isArray(value);
123
+ }
124
+ function parseEntry(path, raw) {
125
+ if (!isRecord(raw) || typeof raw["id"] !== "string" || typeof raw["url"] !== "string") throw new Error(`Manifest entry "${path}" needs string "id" and "url"`);
126
+ return {
127
+ id: raw["id"],
128
+ url: raw["url"],
129
+ title: typeof raw["title"] === "string" ? raw["title"] : "",
130
+ parentPath: typeof raw["parentPath"] === "string" ? raw["parentPath"] : null,
131
+ sortOrder: typeof raw["sortOrder"] === "number" ? raw["sortOrder"] : -1,
132
+ hash: typeof raw["hash"] === "string" ? raw["hash"] : null
133
+ };
134
+ }
135
+ function parseAssetEntries(raw) {
136
+ if (!isRecord(raw)) throw new Error("Manifest assets must be an object");
137
+ return Object.fromEntries(Object.entries(raw).map(([path, e]) => {
138
+ if (!isRecord(e) || typeof e["hash"] !== "string" || typeof e["url"] !== "string") throw new Error(`Manifest asset "${path}" needs string "hash" and "url"`);
139
+ return [path, {
140
+ hash: e["hash"],
141
+ url: e["url"]
142
+ }];
143
+ }));
144
+ }
145
+ function parseEntries(raw) {
146
+ if (!isRecord(raw)) throw new Error("Manifest container must be an object");
147
+ return Object.fromEntries(Object.entries(raw).map(([path, e]) => [path, parseEntry(path, e)]));
148
+ }
149
+ /**
150
+ * Parses a manifest file. Also accepts the spike's unversioned format
151
+ * (`{ "team:<id>": { "<path>": { id, url, hash } } }`).
152
+ */
153
+ function parseManifest(json) {
154
+ const raw = JSON.parse(json);
155
+ if (!isRecord(raw)) throw new Error("Manifest must be a JSON object");
156
+ const containers = raw["version"] === 1 ? raw["containers"] : raw;
157
+ if (raw["version"] !== void 0 && raw["version"] !== 1) throw new Error(`Unsupported manifest version ${String(raw["version"])}`);
158
+ if (!isRecord(containers)) throw new Error("Manifest is missing \"containers\"");
159
+ const assets = raw["version"] === 1 ? raw["assets"] ?? {} : {};
160
+ if (!isRecord(assets)) throw new Error("Manifest \"assets\" must be an object");
161
+ return {
162
+ version: 1,
163
+ containers: Object.fromEntries(Object.entries(containers).map(([key, entries]) => [key, parseEntries(entries)])),
164
+ assets: Object.fromEntries(Object.entries(assets).map(([key, entries]) => [key, parseAssetEntries(entries)]))
165
+ };
166
+ }
167
+ function serializeManifest(manifest) {
168
+ return `${JSON.stringify(manifest, null, 2)}\n`;
169
+ }
170
+ // ../core/src/model.ts
171
+ /** Stable string key for a container, used to scope the manifest. */
172
+ function containerKey(container) {
173
+ return `${container.type}:${container.id}`;
174
+ }
175
+ /** Parses `team:<id>` / `project:<id>`. */
176
+ function parseContainerKey(key) {
177
+ const [type, ...rest] = key.split(":");
178
+ const id = rest.join(":");
179
+ if (type !== "team" && type !== "project" || !id) throw new Error(`Invalid container key "${key}", expected "team:<id>" or "project:<id>"`);
180
+ return {
181
+ type,
182
+ id
183
+ };
184
+ }
185
+ export { serializeManifest as a, parseManifest as i, parseContainerKey as n, layoutPages as o, emptyManifest as r, formatPlan as s, containerKey as t };
@@ -0,0 +1,227 @@
1
+ import { d as stripHtmlAnchors, f as unlinkInPageLinks, r as DocNotFoundError } from "./src-BU0LDvW9.js";
2
+ // ../linear/src/client.ts
3
+ const LINEAR_ENDPOINT = "https://api.linear.app/graphql";
4
+ var LinearApiError = class extends Error {
5
+ status;
6
+ errors;
7
+ constructor(message, status, errors = []) {
8
+ super(message);
9
+ this.name = "LinearApiError";
10
+ this.status = status;
11
+ this.errors = errors;
12
+ }
13
+ };
14
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
15
+ /**
16
+ * Rate-limited requests were rejected before running, so retrying them is safe even for mutations.
17
+ * Other failures (5xx, timeouts) are not retried: a create may already have happened.
18
+ */
19
+ function isRateLimited(status, errors) {
20
+ return status === 429 || (errors ?? []).some((e) => e.extensions?.["code"] === "RATELIMITED");
21
+ }
22
+ /**
23
+ * Minimal Linear GraphQL client. We don't use `@linear/sdk` for document mutations because its
24
+ * published schema lacks `parentDocumentId`, `subDocumentSortOrder` and `teamId`, which the live
25
+ * API accepts (see docs/spike-findings.md, "Live API introspection").
26
+ */
27
+ function createGraphQLClient(options) {
28
+ const doFetch = options.fetch ?? fetch;
29
+ const endpoint = options.endpoint ?? "https://api.linear.app/graphql";
30
+ const maxRetries = options.maxRetries ?? 3;
31
+ const retryDelayMs = options.retryDelayMs ?? 1e3;
32
+ const timeoutMs = options.timeoutMs ?? 3e4;
33
+ const authorization = options.apiKey.startsWith("lin_api_") ? options.apiKey : `Bearer ${options.apiKey}`;
34
+ return async (query, variables = {}) => {
35
+ for (let attempt = 0;; attempt++) {
36
+ const res = await doFetch(endpoint, {
37
+ method: "POST",
38
+ headers: {
39
+ "Content-Type": "application/json",
40
+ Authorization: authorization
41
+ },
42
+ body: JSON.stringify({
43
+ query,
44
+ variables
45
+ }),
46
+ signal: AbortSignal.timeout(timeoutMs)
47
+ });
48
+ const text = await res.text();
49
+ let body;
50
+ let parseError;
51
+ try {
52
+ body = JSON.parse(text);
53
+ } catch (error) {
54
+ parseError = error;
55
+ }
56
+ if (attempt < maxRetries && isRateLimited(res.status, body?.errors)) {
57
+ const retryAfter = Number(res.headers.get("retry-after"));
58
+ await sleep(retryAfter > 0 ? retryAfter * 1e3 : retryDelayMs * 2 ** attempt);
59
+ continue;
60
+ }
61
+ if (body?.errors?.length) throw new LinearApiError(body.errors.map((e) => e.message).join("\n"), res.status, body.errors);
62
+ if (parseError !== void 0) {
63
+ const reason = parseError instanceof Error ? parseError.message : String(parseError);
64
+ throw new LinearApiError(`Linear API returned HTTP ${res.status} with a non-JSON body (${reason}): ${text.slice(0, 200)}`, res.status);
65
+ }
66
+ if (!res.ok || body?.data == null) throw new LinearApiError(`Linear API request failed with HTTP ${res.status}${res.ok ? " (no data in response)" : ""}`, res.status);
67
+ return body.data;
68
+ }
69
+ };
70
+ }
71
+ // ../linear/src/target.ts
72
+ const CREATE = `mutation LinopressCreate($input: DocumentCreateInput!) {
73
+ documentCreate(input: $input) { success document { id url } }
74
+ }`;
75
+ const UPDATE = `mutation LinopressUpdate($id: String!, $input: DocumentUpdateInput!) {
76
+ documentUpdate(id: $id, input: $input) { success document { id trashed archivedAt } }
77
+ }`;
78
+ /** Linear's "delete" is its trash: the doc is archived, flagged `trashed`, and restorable from the UI. */
79
+ const TRASH = `mutation LinopressTrash($id: String!) {
80
+ documentDelete(id: $id) { success }
81
+ }`;
82
+ const UPLOAD = `mutation LinopressUpload($filename: String!, $contentType: String!, $size: Int!) {
83
+ fileUpload(filename: $filename, contentType: $contentType, size: $size) {
84
+ success uploadFile { uploadUrl assetUrl headers { key value } }
85
+ }
86
+ }`;
87
+ const READ = `query LinopressDoc($id: String!) {
88
+ document(id: $id) { id trashed archivedAt }
89
+ }`;
90
+ /**
91
+ * Maps a position to Linear's fields. Top-level docs are ordered by `sortOrder`; sub-documents by
92
+ * `subDocumentSortOrder` under `parentDocumentId`. We send `parentDocumentId: null` to un-nest.
93
+ */
94
+ function positionFields(position) {
95
+ return position.parentId === null ? {
96
+ parentDocumentId: null,
97
+ sortOrder: position.sortOrder
98
+ } : {
99
+ parentDocumentId: position.parentId,
100
+ subDocumentSortOrder: position.sortOrder,
101
+ sortOrder: position.sortOrder
102
+ };
103
+ }
104
+ const NOT_FOUND = /entity not found|could not find|not[ _-]?found/i;
105
+ /**
106
+ * True when every error Linear returned reads as "not found". This alone doesn't say *which*
107
+ * entity is missing (it may be a parent doc), so callers confirm with a read of the doc itself.
108
+ */
109
+ function looksNotFound(error) {
110
+ return error instanceof LinearApiError && error.errors.length > 0 && error.errors.every((e) => NOT_FOUND.test(e.message) || NOT_FOUND.test(String(e.extensions?.["code"] ?? "")));
111
+ }
112
+ const isGone = (doc) => !doc || !!doc.trashed || !!doc.archivedAt;
113
+ /** Linear Documents as a Linopress target, scoped to one team or project. */
114
+ var LinearTarget = class {
115
+ container;
116
+ #request;
117
+ #fetch;
118
+ #timeoutMs;
119
+ constructor(options) {
120
+ this.container = options.container;
121
+ this.#fetch = options.fetch ?? fetch;
122
+ this.#timeoutMs = options.timeoutMs ?? 3e4;
123
+ if (options.request) this.#request = options.request;
124
+ else if (options.apiKey) this.#request = createGraphQLClient({
125
+ ...options,
126
+ apiKey: options.apiKey
127
+ });
128
+ else throw new Error("LinearTarget needs an apiKey (LINEAR_API_KEY) or a request function");
129
+ }
130
+ async create(input) {
131
+ const containerField = this.container.type === "team" ? "teamId" : "projectId";
132
+ const { parentDocumentId, ...position } = positionFields(input);
133
+ const data = await this.#request(CREATE, { input: {
134
+ title: input.title,
135
+ content: input.content,
136
+ [containerField]: this.container.id,
137
+ ...position,
138
+ ...parentDocumentId !== null && { parentDocumentId }
139
+ } });
140
+ const doc = data.documentCreate?.document;
141
+ if (!data.documentCreate?.success || !doc) throw new Error(`documentCreate failed for "${input.title}"`);
142
+ return {
143
+ id: doc.id,
144
+ url: doc.url
145
+ };
146
+ }
147
+ /** Throws `DocNotFoundError` when the doc is deleted, or trashed/archived outside Linopress. */
148
+ async update(id, input) {
149
+ const doc = await this.#mutateUpdate(id, {
150
+ ...input.title !== void 0 && { title: input.title },
151
+ ...input.content !== void 0 && { content: input.content },
152
+ ...input.position && positionFields(input.position)
153
+ });
154
+ if (doc && isGone(doc)) throw new DocNotFoundError(id);
155
+ }
156
+ /**
157
+ * Moves the doc to Linear's trash, which is recoverable from the UI. Linear rejects
158
+ * `documentUpdate` with `trashed: true` ("invalid trashed state"); `documentDelete` is its trash
159
+ * action, and calling it on an already-trashed doc succeeds.
160
+ */
161
+ async archive(id) {
162
+ if (!(await this.#notFoundAware(id, () => this.#request(TRASH, { id }))).documentDelete?.success) throw new Error(`documentDelete failed for ${id}`);
163
+ }
164
+ /**
165
+ * Uploads a file to Linear's storage: `fileUpload` returns a signed URL, the bytes go there with
166
+ * a PUT, and docs reference the returned asset URL (visible to workspace members).
167
+ */
168
+ async uploadAsset(asset) {
169
+ const filename = asset.path.split("/").pop() || asset.path;
170
+ const data = await this.#request(UPLOAD, {
171
+ filename,
172
+ contentType: asset.contentType,
173
+ size: asset.data.byteLength
174
+ });
175
+ const file = data.fileUpload?.uploadFile;
176
+ if (!data.fileUpload?.success || !file) throw new Error(`fileUpload failed for "${asset.path}"`);
177
+ const headers = {
178
+ "Content-Type": asset.contentType,
179
+ "Cache-Control": "public, max-age=31536000"
180
+ };
181
+ for (const { key, value } of file.headers) headers[key] = value;
182
+ const res = await this.#fetch(file.uploadUrl, {
183
+ method: "PUT",
184
+ headers,
185
+ body: asset.data,
186
+ signal: AbortSignal.timeout(this.#timeoutMs)
187
+ });
188
+ if (!res.ok) throw new LinearApiError(`Uploading "${asset.path}" failed with HTTP ${res.status}: ${(await res.text()).slice(0, 200)}`, res.status);
189
+ return file.assetUrl;
190
+ }
191
+ /**
192
+ * Returns the doc's state after the update. Throws `DocNotFoundError` only when a read confirms
193
+ * this doc is gone (deleted, purged, trashed or archived); other "not found" errors pass through.
194
+ */
195
+ async #mutateUpdate(id, input) {
196
+ const data = await this.#notFoundAware(id, () => this.#request(UPDATE, {
197
+ id,
198
+ input
199
+ }));
200
+ if (!data.documentUpdate?.success) throw new Error(`documentUpdate failed for ${id}`);
201
+ return data.documentUpdate.document ?? null;
202
+ }
203
+ async #notFoundAware(id, run) {
204
+ try {
205
+ return await run();
206
+ } catch (error) {
207
+ if (looksNotFound(error) && await this.#confirmGone(id)) throw new DocNotFoundError(id);
208
+ throw error;
209
+ }
210
+ }
211
+ async #confirmGone(id) {
212
+ try {
213
+ const data = await this.#request(READ, { id });
214
+ return isGone(data.document);
215
+ } catch (error) {
216
+ return looksNotFound(error);
217
+ }
218
+ }
219
+ };
220
+ // ../linear/src/transforms.ts
221
+ /**
222
+ * The Markdown clean-up Linear needs (see docs/spike-findings.md, "Rendering"): Linear shows
223
+ * `<a id>` anchors as literal text, and its heading ids are UUIDs, so `#slug` links are dead.
224
+ * Pass these to `plan` / `apply` when the target is a `LinearTarget`.
225
+ */
226
+ const linearTransforms = [stripHtmlAnchors, unlinkInPageLinks];
227
+ export { createGraphQLClient as a, LinearApiError as i, LinearTarget as n, LINEAR_ENDPOINT as r, linearTransforms as t };