@kidecms/wordpress 0.0.0-stage → 0.2.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/src/php.ts ADDED
@@ -0,0 +1,62 @@
1
+ /** Minimal PHP `unserialize()` for WordPress meta/option values. Returns the input unchanged when it isn't serialized. */
2
+ export const maybeUnserialize = (value: unknown): unknown => {
3
+ if (typeof value !== "string" || !/^(a|O|s|i|d|b):|^N;$/.test(value)) return value;
4
+ try {
5
+ const bytes = Buffer.from(value, "utf8");
6
+ const [result, end] = parse(bytes, 0);
7
+ return end === bytes.length ? result : value;
8
+ } catch {
9
+ return value;
10
+ }
11
+ };
12
+
13
+ const readUntil = (b: Buffer, i: number, ch: string): [string, number] => {
14
+ const end = b.indexOf(ch, i);
15
+ if (end < 0) throw new Error("unterminated");
16
+ return [b.toString("utf8", i, end), end + 1];
17
+ };
18
+
19
+ const parse = (b: Buffer, i: number): [unknown, number] => {
20
+ const type = String.fromCharCode(b[i]);
21
+ if (type === "N") return [null, i + 2];
22
+ if (b[i + 1] !== 0x3a) throw new Error("bad");
23
+ i += 2;
24
+ switch (type) {
25
+ case "i":
26
+ case "d": {
27
+ const [n, next] = readUntil(b, i, ";");
28
+ return [Number(n), next];
29
+ }
30
+ case "b": {
31
+ const [n, next] = readUntil(b, i, ";");
32
+ return [n === "1", next];
33
+ }
34
+ case "s": {
35
+ const [len, next] = readUntil(b, i, ":");
36
+ const start = next + 1;
37
+ const end = start + Number(len);
38
+ return [b.toString("utf8", start, end), end + 2];
39
+ }
40
+ case "a":
41
+ case "O": {
42
+ if (type === "O") {
43
+ const [, afterLen] = readUntil(b, i, ":");
44
+ const [, afterName] = readUntil(b, afterLen, ":");
45
+ i = afterName;
46
+ }
47
+ const [count, next] = readUntil(b, i, ":");
48
+ i = next + 1;
49
+ const entries: Array<[unknown, unknown]> = [];
50
+ for (let n = 0; n < Number(count); n++) {
51
+ const [key, afterKey] = parse(b, i);
52
+ const [val, afterVal] = parse(b, afterKey);
53
+ entries.push([key, val]);
54
+ i = afterVal;
55
+ }
56
+ const isList = type === "a" && entries.every(([k], idx) => k === idx);
57
+ return [isList ? entries.map(([, v]) => v) : Object.fromEntries(entries.map(([k, v]) => [String(k), v])), i + 1];
58
+ }
59
+ default:
60
+ throw new Error(`unsupported type ${type}`);
61
+ }
62
+ };