@vedyua/cms 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.
- package/README.md +67 -2
- package/dist/admin-bar.d.ts +12 -0
- package/dist/admin-bar.js +94 -0
- package/dist/admin-bar.js.map +1 -0
- package/dist/admin-entry.d.ts +24 -0
- package/dist/admin-entry.js +140 -0
- package/dist/admin-entry.js.map +1 -0
- package/dist/context.d.ts +50 -0
- package/dist/context.js +260 -0
- package/dist/context.js.map +1 -0
- package/dist/cookies.d.ts +8 -0
- package/dist/cookies.js +37 -0
- package/dist/cookies.js.map +1 -0
- package/dist/define.d.ts +32 -0
- package/dist/define.js +100 -0
- package/dist/define.js.map +1 -0
- package/dist/editable-text.d.ts +20 -0
- package/dist/editable-text.js +114 -0
- package/dist/editable-text.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +61 -0
- package/dist/index.js.map +1 -0
- package/dist/next/create-api.d.ts +39 -0
- package/dist/next/create-api.js +238 -0
- package/dist/next/create-api.js.map +1 -0
- package/dist/next/index.d.ts +7 -0
- package/dist/next/index.js +7 -0
- package/dist/next/index.js.map +1 -0
- package/dist/next/save-handler.d.ts +19 -0
- package/dist/next/save-handler.js +96 -0
- package/dist/next/save-handler.js.map +1 -0
- package/dist/page-settings.d.ts +12 -0
- package/dist/page-settings.js +144 -0
- package/dist/page-settings.js.map +1 -0
- package/dist/path.d.ts +5 -0
- package/dist/path.js +38 -0
- package/dist/path.js.map +1 -0
- package/dist/server/auth-github.d.ts +24 -0
- package/dist/server/auth-github.js +112 -0
- package/dist/server/auth-github.js.map +1 -0
- package/dist/server/auth-password.d.ts +20 -0
- package/dist/server/auth-password.js +41 -0
- package/dist/server/auth-password.js.map +1 -0
- package/dist/server/auth.d.ts +45 -0
- package/dist/server/auth.js +1 -0
- package/dist/server/auth.js.map +1 -0
- package/dist/server/index.d.ts +7 -0
- package/dist/server/index.js +18 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/publish-command.d.ts +37 -0
- package/dist/server/publish-command.js +170 -0
- package/dist/server/publish-command.js.map +1 -0
- package/dist/server/publish-status.d.ts +20 -0
- package/dist/server/publish-status.js +131 -0
- package/dist/server/publish-status.js.map +1 -0
- package/dist/server/publish.d.ts +25 -0
- package/dist/server/publish.js +1 -0
- package/dist/server/publish.js.map +1 -0
- package/dist/server/session.d.ts +21 -0
- package/dist/server/session.js +95 -0
- package/dist/server/session.js.map +1 -0
- package/dist/styles.css +388 -0
- package/dist/types.d.ts +85 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +1 -0
- package/package.json +67 -4
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import {
|
|
4
|
+
clearPublishStatus,
|
|
5
|
+
readPublishStatus,
|
|
6
|
+
releasePublishClaim,
|
|
7
|
+
tryClaimPublish,
|
|
8
|
+
updatePublishClaimPid,
|
|
9
|
+
writePublishStatus
|
|
10
|
+
} from "./publish-status";
|
|
11
|
+
class PublishBusyError extends Error {
|
|
12
|
+
code = "PUBLISH_BUSY";
|
|
13
|
+
constructor(message = "Publish already in progress") {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "PublishBusyError";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function runCommand(command, options) {
|
|
19
|
+
return new Promise((resolve, reject) => {
|
|
20
|
+
const child = spawn(command, {
|
|
21
|
+
cwd: options.cwd,
|
|
22
|
+
env: options.env,
|
|
23
|
+
shell: true,
|
|
24
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
25
|
+
});
|
|
26
|
+
let stdout = "";
|
|
27
|
+
let stderr = "";
|
|
28
|
+
const timer = setTimeout(() => {
|
|
29
|
+
child.kill("SIGTERM");
|
|
30
|
+
reject(new Error(`Publish command timed out after ${options.timeoutMs}ms`));
|
|
31
|
+
}, options.timeoutMs);
|
|
32
|
+
child.stdout.on("data", (chunk) => {
|
|
33
|
+
stdout += String(chunk);
|
|
34
|
+
});
|
|
35
|
+
child.stderr.on("data", (chunk) => {
|
|
36
|
+
stderr += String(chunk);
|
|
37
|
+
});
|
|
38
|
+
child.on("error", (error) => {
|
|
39
|
+
clearTimeout(timer);
|
|
40
|
+
reject(error);
|
|
41
|
+
});
|
|
42
|
+
child.on("close", (code) => {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code: code ?? 1 });
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function commandPublish(options) {
|
|
49
|
+
if (!options.command?.trim()) {
|
|
50
|
+
throw new Error("commandPublish requires a command");
|
|
51
|
+
}
|
|
52
|
+
const cwd = path.resolve(options.cwd ?? process.cwd());
|
|
53
|
+
const timeoutMs = options.timeoutMs ?? 10 * 60 * 1e3;
|
|
54
|
+
const detached = Boolean(options.detached);
|
|
55
|
+
const statusFile = options.statusFile ? path.resolve(options.statusFile) : void 0;
|
|
56
|
+
let localBusy = false;
|
|
57
|
+
return {
|
|
58
|
+
id: "command",
|
|
59
|
+
async status() {
|
|
60
|
+
return readPublishStatus(statusFile);
|
|
61
|
+
},
|
|
62
|
+
async publish(input) {
|
|
63
|
+
if (localBusy) {
|
|
64
|
+
throw new PublishBusyError();
|
|
65
|
+
}
|
|
66
|
+
if (statusFile) {
|
|
67
|
+
const current = readPublishStatus(statusFile);
|
|
68
|
+
if (current.state === "running") {
|
|
69
|
+
throw new PublishBusyError();
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const env = {
|
|
73
|
+
...process.env,
|
|
74
|
+
...options.env,
|
|
75
|
+
CONTENT_CMS_PUBLISH_AUTHOR: input.session.name || input.session.email,
|
|
76
|
+
CONTENT_CMS_PUBLISH_EMAIL: input.session.email,
|
|
77
|
+
CONTENT_CMS_PUBLISH_MESSAGE: input.message
|
|
78
|
+
};
|
|
79
|
+
if (statusFile) {
|
|
80
|
+
env.CONTENT_CMS_PUBLISH_STATUS_FILE = statusFile;
|
|
81
|
+
}
|
|
82
|
+
localBusy = true;
|
|
83
|
+
try {
|
|
84
|
+
if (statusFile) {
|
|
85
|
+
const claimed = tryClaimPublish(statusFile, {
|
|
86
|
+
pid: process.pid,
|
|
87
|
+
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
88
|
+
message: input.message
|
|
89
|
+
});
|
|
90
|
+
if (!claimed) {
|
|
91
|
+
throw new PublishBusyError();
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (detached) {
|
|
95
|
+
const child = spawn(options.command, {
|
|
96
|
+
cwd,
|
|
97
|
+
env,
|
|
98
|
+
shell: true,
|
|
99
|
+
detached: true,
|
|
100
|
+
stdio: "ignore"
|
|
101
|
+
});
|
|
102
|
+
child.unref();
|
|
103
|
+
if (statusFile && child.pid) {
|
|
104
|
+
updatePublishClaimPid(statusFile, child.pid, input.message);
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
ok: true,
|
|
108
|
+
commitSha: `cmd-${Date.now().toString(36)}`,
|
|
109
|
+
message: `${input.message} (rebuild started in background)`,
|
|
110
|
+
pending: true
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
const result = await runCommand(options.command, { cwd, env, timeoutMs });
|
|
115
|
+
if (result.code !== 0) {
|
|
116
|
+
if (statusFile) {
|
|
117
|
+
writePublishStatus(statusFile, {
|
|
118
|
+
state: "failed",
|
|
119
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
120
|
+
message: result.stderr || result.stdout || `Publish command failed (${result.code})`
|
|
121
|
+
});
|
|
122
|
+
releasePublishClaim(statusFile);
|
|
123
|
+
}
|
|
124
|
+
throw new Error(result.stderr || result.stdout || `Publish command failed (${result.code})`);
|
|
125
|
+
}
|
|
126
|
+
if (statusFile) {
|
|
127
|
+
writePublishStatus(statusFile, {
|
|
128
|
+
state: "idle",
|
|
129
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
130
|
+
message: input.message
|
|
131
|
+
});
|
|
132
|
+
releasePublishClaim(statusFile);
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
ok: true,
|
|
136
|
+
commitSha: `cmd-${Date.now().toString(36)}`,
|
|
137
|
+
message: input.message,
|
|
138
|
+
pending: false
|
|
139
|
+
};
|
|
140
|
+
} catch (error) {
|
|
141
|
+
if (statusFile && !(error instanceof PublishBusyError)) {
|
|
142
|
+
const message = error instanceof Error ? error.message : "Publish failed";
|
|
143
|
+
writePublishStatus(statusFile, {
|
|
144
|
+
state: "failed",
|
|
145
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
146
|
+
message
|
|
147
|
+
});
|
|
148
|
+
releasePublishClaim(statusFile);
|
|
149
|
+
}
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (error instanceof PublishBusyError) {
|
|
154
|
+
throw error;
|
|
155
|
+
}
|
|
156
|
+
if (detached && statusFile) {
|
|
157
|
+
clearPublishStatus(statusFile);
|
|
158
|
+
}
|
|
159
|
+
throw error;
|
|
160
|
+
} finally {
|
|
161
|
+
localBusy = false;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
export {
|
|
167
|
+
PublishBusyError,
|
|
168
|
+
commandPublish
|
|
169
|
+
};
|
|
170
|
+
//# sourceMappingURL=publish-command.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/publish-command.ts"],"sourcesContent":["import { spawn } from \"node:child_process\";\nimport path from \"node:path\";\n\nimport type { PublishAdapter, PublishInput, PublishResult } from \"./publish\";\nimport {\n clearPublishStatus,\n readPublishStatus,\n releasePublishClaim,\n tryClaimPublish,\n updatePublishClaimPid,\n writePublishStatus,\n} from \"./publish-status\";\n\nexport type CommandPublishOptions = {\n /**\n * Shell command to run after content files are saved.\n * Example: `DEPLOY_SKIP_PULL=1 bash scripts/deploy.sh storefront`\n */\n command: string;\n /** Working directory for the command. Defaults to `process.cwd()`. */\n cwd?: string;\n /**\n * When true, start the command in the background and return immediately.\n * Useful for long rebuilds that would otherwise time out the HTTP request.\n * @default false\n */\n detached?: boolean;\n /** Max wait when `detached` is false. @default 10 minutes */\n timeoutMs?: number;\n env?: Record<string, string>;\n /**\n * JSON status file used to lock / poll background publishes.\n * Shared with the publish shell script when possible.\n */\n statusFile?: string;\n};\n\nclass PublishBusyError extends Error {\n readonly code = \"PUBLISH_BUSY\";\n\n constructor(message = \"Publish already in progress\") {\n super(message);\n this.name = \"PublishBusyError\";\n }\n}\n\nfunction runCommand(\n command: string,\n options: { cwd: string; env: NodeJS.ProcessEnv; timeoutMs: number },\n): Promise<{ stdout: string; stderr: string; code: number }> {\n return new Promise((resolve, reject) => {\n const child = spawn(command, {\n cwd: options.cwd,\n env: options.env,\n shell: true,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n const timer = setTimeout(() => {\n child.kill(\"SIGTERM\");\n reject(new Error(`Publish command timed out after ${options.timeoutMs}ms`));\n }, options.timeoutMs);\n\n child.stdout.on(\"data\", (chunk: Buffer | string) => {\n stdout += String(chunk);\n });\n child.stderr.on(\"data\", (chunk: Buffer | string) => {\n stderr += String(chunk);\n });\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(error);\n });\n child.on(\"close\", (code: number | null) => {\n clearTimeout(timer);\n resolve({ stdout: stdout.trim(), stderr: stderr.trim(), code: code ?? 1 });\n });\n });\n}\n\n/**\n * Publish adapter that runs a local command (rebuild, rsync, etc.) — no git remote required.\n */\nexport function commandPublish(options: CommandPublishOptions): PublishAdapter {\n if (!options.command?.trim()) {\n throw new Error(\"commandPublish requires a command\");\n }\n\n const cwd = path.resolve(options.cwd ?? process.cwd());\n const timeoutMs = options.timeoutMs ?? 10 * 60 * 1000;\n const detached = Boolean(options.detached);\n const statusFile = options.statusFile ? path.resolve(options.statusFile) : undefined;\n\n // Same-process gate for double-clicks before the status file is written.\n let localBusy = false;\n\n return {\n id: \"command\",\n async status() {\n return readPublishStatus(statusFile);\n },\n async publish(input: PublishInput): Promise<PublishResult> {\n if (localBusy) {\n throw new PublishBusyError();\n }\n\n if (statusFile) {\n const current = readPublishStatus(statusFile);\n if (current.state === \"running\") {\n throw new PublishBusyError();\n }\n }\n\n const env: NodeJS.ProcessEnv = {\n ...process.env,\n ...options.env,\n CONTENT_CMS_PUBLISH_AUTHOR: input.session.name || input.session.email,\n CONTENT_CMS_PUBLISH_EMAIL: input.session.email,\n CONTENT_CMS_PUBLISH_MESSAGE: input.message,\n };\n if (statusFile) {\n env.CONTENT_CMS_PUBLISH_STATUS_FILE = statusFile;\n }\n\n localBusy = true;\n\n try {\n if (statusFile) {\n const claimed = tryClaimPublish(statusFile, {\n pid: process.pid,\n startedAt: new Date().toISOString(),\n message: input.message,\n });\n if (!claimed) {\n throw new PublishBusyError();\n }\n }\n\n if (detached) {\n const child = spawn(options.command, {\n cwd,\n env,\n shell: true,\n detached: true,\n stdio: \"ignore\",\n });\n child.unref();\n\n if (statusFile && child.pid) {\n updatePublishClaimPid(statusFile, child.pid, input.message);\n }\n\n return {\n ok: true,\n commitSha: `cmd-${Date.now().toString(36)}`,\n message: `${input.message} (rebuild started in background)`,\n pending: true,\n };\n }\n\n try {\n const result = await runCommand(options.command, { cwd, env, timeoutMs });\n if (result.code !== 0) {\n if (statusFile) {\n writePublishStatus(statusFile, {\n state: \"failed\",\n finishedAt: new Date().toISOString(),\n message: result.stderr || result.stdout || `Publish command failed (${result.code})`,\n });\n releasePublishClaim(statusFile);\n }\n throw new Error(result.stderr || result.stdout || `Publish command failed (${result.code})`);\n }\n\n if (statusFile) {\n writePublishStatus(statusFile, {\n state: \"idle\",\n finishedAt: new Date().toISOString(),\n message: input.message,\n });\n releasePublishClaim(statusFile);\n }\n\n return {\n ok: true,\n commitSha: `cmd-${Date.now().toString(36)}`,\n message: input.message,\n pending: false,\n };\n } catch (error) {\n if (statusFile && !(error instanceof PublishBusyError)) {\n const message = error instanceof Error ? error.message : \"Publish failed\";\n writePublishStatus(statusFile, {\n state: \"failed\",\n finishedAt: new Date().toISOString(),\n message,\n });\n releasePublishClaim(statusFile);\n }\n throw error;\n }\n } catch (error) {\n if (error instanceof PublishBusyError) {\n throw error;\n }\n // Spawn failed before shell could take over — release the claim.\n if (detached && statusFile) {\n clearPublishStatus(statusFile);\n }\n throw error;\n } finally {\n localBusy = false;\n }\n },\n };\n}\n\nexport { PublishBusyError };\n"],"mappings":"AAAA,SAAS,aAAa;AACtB,OAAO,UAAU;AAGjB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA0BP,MAAM,yBAAyB,MAAM;AAAA,EAC1B,OAAO;AAAA,EAEhB,YAAY,UAAU,+BAA+B;AACnD,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEA,SAAS,WACP,SACA,SAC2D;AAC3D,SAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,UAAM,QAAQ,MAAM,SAAS;AAAA,MAC3B,KAAK,QAAQ;AAAA,MACb,KAAK,QAAQ;AAAA,MACb,OAAO;AAAA,MACP,OAAO,CAAC,UAAU,QAAQ,MAAM;AAAA,IAClC,CAAC;AAED,QAAI,SAAS;AACb,QAAI,SAAS;AACb,UAAM,QAAQ,WAAW,MAAM;AAC7B,YAAM,KAAK,SAAS;AACpB,aAAO,IAAI,MAAM,mCAAmC,QAAQ,SAAS,IAAI,CAAC;AAAA,IAC5E,GAAG,QAAQ,SAAS;AAEpB,UAAM,OAAO,GAAG,QAAQ,CAAC,UAA2B;AAClD,gBAAU,OAAO,KAAK;AAAA,IACxB,CAAC;AACD,UAAM,OAAO,GAAG,QAAQ,CAAC,UAA2B;AAClD,gBAAU,OAAO,KAAK;AAAA,IACxB,CAAC;AACD,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O;AAAA,YACL,IAAI;AAAA,YACJ,WAAW,OAAO,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC;AAAA,YACzC,SAAS,MAAM;AAAA,YACf,SAAS;AAAA,UACX;AAAA,QACF,SAAS,OAAO;AACd,cAAI,cAAc,EAAE,iBAAiB,mBAAmB;AACtD,kBAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU;AACzD,+BAAmB,YAAY;AAAA,cAC7B,OAAO;AAAA,cACP,aAAY,oBAAI,KAAK,GAAE,YAAY;AAAA,cACnC;AAAA,YACF,CAAC;AACD,gCAAoB,UAAU;AAAA,UAChC;AACA,gBAAM;AAAA,QACR;AAAA,MACF,SAAS,OAAO;AACd,YAAI,iBAAiB,kBAAkB;AACrC,gBAAM;AAAA,QACR;AAEA,YAAI,YAAY,YAAY;AAC1B,6BAAmB,UAAU;AAAA,QAC/B;AACA,cAAM;AAAA,MACR,UAAE;AACA,oBAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
type PublishJobState = "idle" | "running" | "failed";
|
|
2
|
+
type PublishStatus = {
|
|
3
|
+
state: PublishJobState;
|
|
4
|
+
startedAt?: string;
|
|
5
|
+
finishedAt?: string;
|
|
6
|
+
message?: string;
|
|
7
|
+
pid?: number;
|
|
8
|
+
};
|
|
9
|
+
declare function readPublishStatus(statusFile: string | undefined): PublishStatus;
|
|
10
|
+
declare function writePublishStatus(statusFile: string, status: PublishStatus): void;
|
|
11
|
+
declare function releasePublishClaim(statusFile: string | undefined): void;
|
|
12
|
+
declare function clearPublishStatus(statusFile: string | undefined): void;
|
|
13
|
+
/**
|
|
14
|
+
* Atomically claim the publish slot (`statusFile.lock` with O_EXCL).
|
|
15
|
+
* Returns false if another live job already holds it.
|
|
16
|
+
*/
|
|
17
|
+
declare function tryClaimPublish(statusFile: string, claim: Omit<PublishStatus, "state">): boolean;
|
|
18
|
+
declare function updatePublishClaimPid(statusFile: string, pid: number, message?: string): void;
|
|
19
|
+
|
|
20
|
+
export { type PublishJobState, type PublishStatus, clearPublishStatus, readPublishStatus, releasePublishClaim, tryClaimPublish, updatePublishClaimPid, writePublishStatus };
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { existsSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
function claimFileFor(statusFile) {
|
|
3
|
+
return `${statusFile}.lock`;
|
|
4
|
+
}
|
|
5
|
+
function isPidAlive(pid) {
|
|
6
|
+
if (!pid || pid <= 0) return false;
|
|
7
|
+
try {
|
|
8
|
+
process.kill(pid, 0);
|
|
9
|
+
return true;
|
|
10
|
+
} catch {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function readClaimPid(claimFile) {
|
|
15
|
+
try {
|
|
16
|
+
const raw = readFileSync(claimFile, "utf8").trim();
|
|
17
|
+
const pid = Number.parseInt(raw, 10);
|
|
18
|
+
return Number.isFinite(pid) ? pid : void 0;
|
|
19
|
+
} catch {
|
|
20
|
+
return void 0;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function readPublishStatus(statusFile) {
|
|
24
|
+
if (!statusFile || !existsSync(statusFile)) {
|
|
25
|
+
const claimFile = statusFile ? claimFileFor(statusFile) : void 0;
|
|
26
|
+
if (claimFile && existsSync(claimFile)) {
|
|
27
|
+
const pid = readClaimPid(claimFile);
|
|
28
|
+
if (isPidAlive(pid)) {
|
|
29
|
+
return { state: "running", pid };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return { state: "idle" };
|
|
33
|
+
}
|
|
34
|
+
try {
|
|
35
|
+
const raw = readFileSync(statusFile, "utf8");
|
|
36
|
+
const parsed = JSON.parse(raw);
|
|
37
|
+
const state = parsed.state === "running" || parsed.state === "failed" ? parsed.state : "idle";
|
|
38
|
+
const status = {
|
|
39
|
+
state,
|
|
40
|
+
startedAt: typeof parsed.startedAt === "string" ? parsed.startedAt : void 0,
|
|
41
|
+
finishedAt: typeof parsed.finishedAt === "string" ? parsed.finishedAt : void 0,
|
|
42
|
+
message: typeof parsed.message === "string" ? parsed.message : void 0,
|
|
43
|
+
pid: typeof parsed.pid === "number" ? parsed.pid : void 0
|
|
44
|
+
};
|
|
45
|
+
if (status.state === "running") {
|
|
46
|
+
const claimFile = claimFileFor(statusFile);
|
|
47
|
+
const claimPid = existsSync(claimFile) ? readClaimPid(claimFile) : void 0;
|
|
48
|
+
const pid = status.pid ?? claimPid;
|
|
49
|
+
if (pid != null && !isPidAlive(pid)) {
|
|
50
|
+
releasePublishClaim(statusFile);
|
|
51
|
+
return {
|
|
52
|
+
state: "idle",
|
|
53
|
+
finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
54
|
+
message: "Previous publish process is no longer running",
|
|
55
|
+
pid
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return status;
|
|
60
|
+
} catch {
|
|
61
|
+
return { state: "idle" };
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function writePublishStatus(statusFile, status) {
|
|
65
|
+
writeFileSync(statusFile, `${JSON.stringify(status)}
|
|
66
|
+
`, "utf8");
|
|
67
|
+
}
|
|
68
|
+
function releasePublishClaim(statusFile) {
|
|
69
|
+
if (!statusFile) return;
|
|
70
|
+
const claimFile = claimFileFor(statusFile);
|
|
71
|
+
try {
|
|
72
|
+
if (existsSync(claimFile)) unlinkSync(claimFile);
|
|
73
|
+
} catch {
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function clearPublishStatus(statusFile) {
|
|
77
|
+
if (!statusFile) return;
|
|
78
|
+
releasePublishClaim(statusFile);
|
|
79
|
+
if (!existsSync(statusFile)) return;
|
|
80
|
+
try {
|
|
81
|
+
unlinkSync(statusFile);
|
|
82
|
+
} catch {
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function tryClaimPublish(statusFile, claim) {
|
|
86
|
+
const claimFile = claimFileFor(statusFile);
|
|
87
|
+
const pid = claim.pid ?? process.pid;
|
|
88
|
+
for (let attempt = 0; attempt < 2; attempt += 1) {
|
|
89
|
+
try {
|
|
90
|
+
writeFileSync(claimFile, `${pid}
|
|
91
|
+
`, { flag: "wx" });
|
|
92
|
+
writePublishStatus(statusFile, {
|
|
93
|
+
state: "running",
|
|
94
|
+
startedAt: claim.startedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
95
|
+
message: claim.message,
|
|
96
|
+
pid
|
|
97
|
+
});
|
|
98
|
+
return true;
|
|
99
|
+
} catch {
|
|
100
|
+
const holder = readClaimPid(claimFile);
|
|
101
|
+
if (isPidAlive(holder)) return false;
|
|
102
|
+
try {
|
|
103
|
+
unlinkSync(claimFile);
|
|
104
|
+
} catch {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
function updatePublishClaimPid(statusFile, pid, message) {
|
|
112
|
+
const claimFile = claimFileFor(statusFile);
|
|
113
|
+
writeFileSync(claimFile, `${pid}
|
|
114
|
+
`, "utf8");
|
|
115
|
+
const current = readPublishStatus(statusFile);
|
|
116
|
+
writePublishStatus(statusFile, {
|
|
117
|
+
state: "running",
|
|
118
|
+
startedAt: current.startedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
|
|
119
|
+
message: message ?? current.message,
|
|
120
|
+
pid
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
export {
|
|
124
|
+
clearPublishStatus,
|
|
125
|
+
readPublishStatus,
|
|
126
|
+
releasePublishClaim,
|
|
127
|
+
tryClaimPublish,
|
|
128
|
+
updatePublishClaimPid,
|
|
129
|
+
writePublishStatus
|
|
130
|
+
};
|
|
131
|
+
//# sourceMappingURL=publish-status.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/publish-status.ts"],"sourcesContent":["import { existsSync, readFileSync, unlinkSync, writeFileSync } from \"node:fs\";\n\nexport type PublishJobState = \"idle\" | \"running\" | \"failed\";\n\nexport type PublishStatus = {\n state: PublishJobState;\n startedAt?: string;\n finishedAt?: string;\n message?: string;\n pid?: number;\n};\n\nfunction claimFileFor(statusFile: string) {\n return `${statusFile}.lock`;\n}\n\nfunction isPidAlive(pid: number | undefined): boolean {\n if (!pid || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction readClaimPid(claimFile: string): number | undefined {\n try {\n const raw = readFileSync(claimFile, \"utf8\").trim();\n const pid = Number.parseInt(raw, 10);\n return Number.isFinite(pid) ? pid : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function readPublishStatus(statusFile: string | undefined): PublishStatus {\n if (!statusFile || !existsSync(statusFile)) {\n const claimFile = statusFile ? claimFileFor(statusFile) : undefined;\n if (claimFile && existsSync(claimFile)) {\n const pid = readClaimPid(claimFile);\n if (isPidAlive(pid)) {\n return { state: \"running\", pid };\n }\n }\n return { state: \"idle\" };\n }\n\n try {\n const raw = readFileSync(statusFile, \"utf8\");\n const parsed = JSON.parse(raw) as Partial<PublishStatus>;\n const state = parsed.state === \"running\" || parsed.state === \"failed\" ? parsed.state : \"idle\";\n const status: PublishStatus = {\n state,\n startedAt: typeof parsed.startedAt === \"string\" ? parsed.startedAt : undefined,\n finishedAt: typeof parsed.finishedAt === \"string\" ? parsed.finishedAt : undefined,\n message: typeof parsed.message === \"string\" ? parsed.message : undefined,\n pid: typeof parsed.pid === \"number\" ? parsed.pid : undefined,\n };\n\n if (status.state === \"running\") {\n const claimFile = claimFileFor(statusFile);\n const claimPid = existsSync(claimFile) ? readClaimPid(claimFile) : undefined;\n const pid = status.pid ?? claimPid;\n if (pid != null && !isPidAlive(pid)) {\n releasePublishClaim(statusFile);\n return {\n state: \"idle\",\n finishedAt: new Date().toISOString(),\n message: \"Previous publish process is no longer running\",\n pid,\n };\n }\n }\n\n return status;\n } catch {\n return { state: \"idle\" };\n }\n}\n\nexport function writePublishStatus(statusFile: string, status: PublishStatus) {\n writeFileSync(statusFile, `${JSON.stringify(status)}\\n`, \"utf8\");\n}\n\nexport function releasePublishClaim(statusFile: string | undefined) {\n if (!statusFile) return;\n const claimFile = claimFileFor(statusFile);\n try {\n if (existsSync(claimFile)) unlinkSync(claimFile);\n } catch {\n // ignore\n }\n}\n\nexport function clearPublishStatus(statusFile: string | undefined) {\n if (!statusFile) return;\n releasePublishClaim(statusFile);\n if (!existsSync(statusFile)) return;\n try {\n unlinkSync(statusFile);\n } catch {\n // ignore\n }\n}\n\n/**\n * Atomically claim the publish slot (`statusFile.lock` with O_EXCL).\n * Returns false if another live job already holds it.\n */\nexport function tryClaimPublish(statusFile: string, claim: Omit<PublishStatus, \"state\">): boolean {\n const claimFile = claimFileFor(statusFile);\n const pid = claim.pid ?? process.pid;\n\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n writeFileSync(claimFile, `${pid}\\n`, { flag: \"wx\" });\n writePublishStatus(statusFile, {\n state: \"running\",\n startedAt: claim.startedAt ?? new Date().toISOString(),\n message: claim.message,\n pid,\n });\n return true;\n } catch {\n const holder = readClaimPid(claimFile);\n if (isPidAlive(holder)) return false;\n try {\n unlinkSync(claimFile);\n } catch {\n return false;\n }\n }\n }\n\n return false;\n}\n\nexport function updatePublishClaimPid(statusFile: string, pid: number, message?: string) {\n const claimFile = claimFileFor(statusFile);\n writeFileSync(claimFile, `${pid}\\n`, \"utf8\");\n const current = readPublishStatus(statusFile);\n writePublishStatus(statusFile, {\n state: \"running\",\n startedAt: current.startedAt ?? new Date().toISOString(),\n message: message ?? current.message,\n pid,\n });\n}\n"],"mappings":"AAAA,SAAS,YAAY,cAAc,YAAY,qBAAqB;AAYpE,SAAS,aAAa,YAAoB;AACxC,SAAO,GAAG,UAAU;AACtB;AAEA,SAAS,WAAW,KAAkC;AACpD,MAAI,CAAC,OAAO,OAAO,EAAG,QAAO;AAC7B,MAAI;AACF,YAAQ,KAAK,KAAK,CAAC;AACnB,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O,SAAS,sBAAsB,YAAoB,KAAa,SAAkB;AACvF,QAAM,YAAY,aAAa,UAAU;AACzC,gBAAc,WAAW,GAAG,GAAG;AAAA,GAAM,MAAM;AAC3C,QAAM,UAAU,kBAAkB,UAAU;AAC5C,qBAAmB,YAAY;AAAA,IAC7B,OAAO;AAAA,IACP,WAAW,QAAQ,cAAa,oBAAI,KAAK,GAAE,YAAY;AAAA,IACvD,SAAS,WAAW,QAAQ;AAAA,IAC5B;AAAA,EACF,CAAC;AACH;","names":[]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ContentSession } from './auth.js';
|
|
2
|
+
import { PublishStatus } from './publish-status.js';
|
|
3
|
+
export { PublishJobState } from './publish-status.js';
|
|
4
|
+
|
|
5
|
+
type PublishInput = {
|
|
6
|
+
message: string;
|
|
7
|
+
session: ContentSession;
|
|
8
|
+
/** Relative paths already changed on disk (optional hint for adapters) */
|
|
9
|
+
paths?: string[];
|
|
10
|
+
};
|
|
11
|
+
type PublishResult = {
|
|
12
|
+
ok: true;
|
|
13
|
+
commitSha: string;
|
|
14
|
+
message: string;
|
|
15
|
+
/** True when rebuild continues in the background after the HTTP response. */
|
|
16
|
+
pending?: boolean;
|
|
17
|
+
};
|
|
18
|
+
type PublishAdapter = {
|
|
19
|
+
id: string;
|
|
20
|
+
publish(input: PublishInput): Promise<PublishResult>;
|
|
21
|
+
/** Optional live status for UI lock / polling while a background publish runs. */
|
|
22
|
+
status?: () => Promise<PublishStatus>;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export { type PublishAdapter, type PublishInput, type PublishResult, PublishStatus };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
//# sourceMappingURL=publish.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ContentSession } from './auth.js';
|
|
2
|
+
|
|
3
|
+
type SessionStoreOptions = {
|
|
4
|
+
secret: string;
|
|
5
|
+
/** @default "scms_session" */
|
|
6
|
+
cookieName?: string;
|
|
7
|
+
/** Session lifetime in seconds. @default 12 hours */
|
|
8
|
+
maxAgeSeconds?: number;
|
|
9
|
+
};
|
|
10
|
+
type SessionStore = {
|
|
11
|
+
cookieName: string;
|
|
12
|
+
maxAgeSeconds: number;
|
|
13
|
+
read(request: Request): ContentSession | null;
|
|
14
|
+
readCookieHeader(cookieHeader: string | null | undefined): ContentSession | null;
|
|
15
|
+
serialize(session: ContentSession): string;
|
|
16
|
+
clearCookieHeader(): string;
|
|
17
|
+
sessionCookieHeader(session: ContentSession): string;
|
|
18
|
+
};
|
|
19
|
+
declare function createSessionStore(options: SessionStoreOptions): SessionStore;
|
|
20
|
+
|
|
21
|
+
export { type SessionStore, type SessionStoreOptions, createSessionStore };
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
function b64url(input) {
|
|
3
|
+
return Buffer.from(input).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
|
|
4
|
+
}
|
|
5
|
+
function fromB64url(input) {
|
|
6
|
+
const padded = input.replace(/-/g, "+").replace(/_/g, "/");
|
|
7
|
+
const pad = padded.length % 4 === 0 ? "" : "=".repeat(4 - padded.length % 4);
|
|
8
|
+
return Buffer.from(padded + pad, "base64").toString("utf8");
|
|
9
|
+
}
|
|
10
|
+
function sign(secret, payload) {
|
|
11
|
+
return b64url(createHmac("sha256", secret).update(payload).digest());
|
|
12
|
+
}
|
|
13
|
+
function safeEqual(a, b) {
|
|
14
|
+
const left = Buffer.from(a);
|
|
15
|
+
const right = Buffer.from(b);
|
|
16
|
+
if (left.length !== right.length) return false;
|
|
17
|
+
return timingSafeEqual(left, right);
|
|
18
|
+
}
|
|
19
|
+
function parseCookieHeader(cookieHeader, name) {
|
|
20
|
+
if (!cookieHeader) return null;
|
|
21
|
+
for (const part of cookieHeader.split(";")) {
|
|
22
|
+
const trimmed = part.trim();
|
|
23
|
+
const eq = trimmed.indexOf("=");
|
|
24
|
+
if (eq === -1) continue;
|
|
25
|
+
if (trimmed.slice(0, eq) === name) {
|
|
26
|
+
return decodeURIComponent(trimmed.slice(eq + 1));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
function cookieAttributes(maxAge) {
|
|
32
|
+
const secure = true;
|
|
33
|
+
return `Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
|
|
34
|
+
}
|
|
35
|
+
function createSessionStore(options) {
|
|
36
|
+
if (!options.secret || options.secret.length < 16) {
|
|
37
|
+
throw new Error("session secret must be at least 16 characters");
|
|
38
|
+
}
|
|
39
|
+
const cookieName = options.cookieName ?? "scms_session";
|
|
40
|
+
const maxAgeSeconds = options.maxAgeSeconds ?? 60 * 60 * 12;
|
|
41
|
+
function serialize(session) {
|
|
42
|
+
const payload = {
|
|
43
|
+
...session,
|
|
44
|
+
exp: Math.floor(Date.now() / 1e3) + maxAgeSeconds
|
|
45
|
+
};
|
|
46
|
+
const body = b64url(JSON.stringify(payload));
|
|
47
|
+
const signature = sign(options.secret, body);
|
|
48
|
+
return `${body}.${signature}`;
|
|
49
|
+
}
|
|
50
|
+
function readToken(token) {
|
|
51
|
+
if (!token) return null;
|
|
52
|
+
const [body, signature] = token.split(".");
|
|
53
|
+
if (!body || !signature) return null;
|
|
54
|
+
const expected = sign(options.secret, body);
|
|
55
|
+
if (!safeEqual(signature, expected)) return null;
|
|
56
|
+
try {
|
|
57
|
+
const payload = JSON.parse(fromB64url(body));
|
|
58
|
+
if (!payload?.exp || payload.exp < Math.floor(Date.now() / 1e3)) return null;
|
|
59
|
+
if (!payload.id || !payload.email || !payload.provider) return null;
|
|
60
|
+
return {
|
|
61
|
+
id: payload.id,
|
|
62
|
+
name: payload.name || payload.email,
|
|
63
|
+
email: payload.email,
|
|
64
|
+
username: payload.username,
|
|
65
|
+
avatarUrl: payload.avatarUrl,
|
|
66
|
+
provider: payload.provider
|
|
67
|
+
};
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
cookieName,
|
|
74
|
+
maxAgeSeconds,
|
|
75
|
+
read(request) {
|
|
76
|
+
return readToken(parseCookieHeader(request.headers.get("cookie"), cookieName));
|
|
77
|
+
},
|
|
78
|
+
readCookieHeader(cookieHeader) {
|
|
79
|
+
return readToken(parseCookieHeader(cookieHeader ?? null, cookieName));
|
|
80
|
+
},
|
|
81
|
+
serialize,
|
|
82
|
+
clearCookieHeader() {
|
|
83
|
+
return `${cookieName}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
|
|
84
|
+
},
|
|
85
|
+
sessionCookieHeader(session) {
|
|
86
|
+
const value = encodeURIComponent(serialize(session));
|
|
87
|
+
void cookieAttributes;
|
|
88
|
+
return `${cookieName}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}`;
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
export {
|
|
93
|
+
createSessionStore
|
|
94
|
+
};
|
|
95
|
+
//# sourceMappingURL=session.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/session.ts"],"sourcesContent":["import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport type { ContentSession } from \"./auth\";\n\nexport type SessionStoreOptions = {\n secret: string;\n /** @default \"scms_session\" */\n cookieName?: string;\n /** Session lifetime in seconds. @default 12 hours */\n maxAgeSeconds?: number;\n};\n\ntype SessionPayload = ContentSession & {\n exp: number;\n username?: string;\n};\n\nexport type SessionStore = {\n cookieName: string;\n maxAgeSeconds: number;\n read(request: Request): ContentSession | null;\n readCookieHeader(cookieHeader: string | null | undefined): ContentSession | null;\n serialize(session: ContentSession): string;\n clearCookieHeader(): string;\n sessionCookieHeader(session: ContentSession): string;\n};\n\nfunction b64url(input: string | Buffer) {\n return Buffer.from(input)\n .toString(\"base64\")\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/g, \"\");\n}\n\nfunction fromB64url(input: string) {\n const padded = input.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const pad = padded.length % 4 === 0 ? \"\" : \"=\".repeat(4 - (padded.length % 4));\n return Buffer.from(padded + pad, \"base64\").toString(\"utf8\");\n}\n\nfunction sign(secret: string, payload: string) {\n return b64url(createHmac(\"sha256\", secret).update(payload).digest());\n}\n\nfunction safeEqual(a: string, b: string) {\n const left = Buffer.from(a);\n const right = Buffer.from(b);\n if (left.length !== right.length) return false;\n return timingSafeEqual(left, right);\n}\n\nfunction parseCookieHeader(cookieHeader: string | null, name: string): string | null {\n if (!cookieHeader) return null;\n for (const part of cookieHeader.split(\";\")) {\n const trimmed = part.trim();\n const eq = trimmed.indexOf(\"=\");\n if (eq === -1) continue;\n if (trimmed.slice(0, eq) === name) {\n return decodeURIComponent(trimmed.slice(eq + 1));\n }\n }\n return null;\n}\n\nfunction cookieAttributes(maxAge: number) {\n const secure = true; // callers may be on http localhost; SameSite=Lax still works without Secure in practice\n // Use Secure only when not explicitly local — keep simple: SameSite=Lax, Path=/\n return `Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;\n}\n\nexport function createSessionStore(options: SessionStoreOptions): SessionStore {\n if (!options.secret || options.secret.length < 16) {\n throw new Error(\"session secret must be at least 16 characters\");\n }\n\n const cookieName = options.cookieName ?? \"scms_session\";\n const maxAgeSeconds = options.maxAgeSeconds ?? 60 * 60 * 12;\n\n function serialize(session: ContentSession): string {\n const payload: SessionPayload = {\n ...session,\n exp: Math.floor(Date.now() / 1000) + maxAgeSeconds,\n };\n const body = b64url(JSON.stringify(payload));\n const signature = sign(options.secret, body);\n return `${body}.${signature}`;\n }\n\n function readToken(token: string | null): ContentSession | null {\n if (!token) return null;\n const [body, signature] = token.split(\".\");\n if (!body || !signature) return null;\n const expected = sign(options.secret, body);\n if (!safeEqual(signature, expected)) return null;\n try {\n const payload = JSON.parse(fromB64url(body)) as SessionPayload;\n if (!payload?.exp || payload.exp < Math.floor(Date.now() / 1000)) return null;\n if (!payload.id || !payload.email || !payload.provider) return null;\n return {\n id: payload.id,\n name: payload.name || payload.email,\n email: payload.email,\n username: payload.username,\n avatarUrl: payload.avatarUrl,\n provider: payload.provider,\n };\n } catch {\n return null;\n }\n }\n\n return {\n cookieName,\n maxAgeSeconds,\n read(request) {\n return readToken(parseCookieHeader(request.headers.get(\"cookie\"), cookieName));\n },\n readCookieHeader(cookieHeader) {\n return readToken(parseCookieHeader(cookieHeader ?? null, cookieName));\n },\n serialize,\n clearCookieHeader() {\n return `${cookieName}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;\n },\n sessionCookieHeader(session) {\n const value = encodeURIComponent(serialize(session));\n // Avoid forcing Secure on localhost HTTP; browsers accept Lax cookies without Secure.\n void cookieAttributes;\n return `${cookieName}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}`;\n },\n };\n}\n"],"mappings":"AAAA,SAAS,YAAY,uBAAuB;AA2B5C,SAAS,OAAO,OAAwB;AACtC,SAAO,OAAO,KAAK,KAAK,EACrB,SAAS,QAAQ,EACjB,QAAQ,OAAO,GAAG,EAClB,QAAQ,OAAO,GAAG,EAClB,QAAQ,QAAQ,EAAE;AACvB;AAEA,SAAS,WAAW,OAAe;AACjC,QAAM,SAAS,MAAM,QAAQ,MAAM,GAAG,EAAE,QAAQ,MAAM,GAAG;AACzD,QAAM,MAAM,OAAO,SAAS,MAAM,IAAI,KAAK,IAAI,OAAO,IAAK,OAAO,SAAS,CAAE;AAC7E,SAAO,OAAO,KAAK,SAAS,KAAK,QAAQ,EAAE,SAAS,MAAM;AAC5D;AAEA,SAAS,KAAK,QAAgB,SAAiB;AAC7C,SAAO,OAAO,WAAW,UAAU,MAAM,EAAE,OAAO,OAAO,EAAE,OAAO,CAAC;AACrE;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