@joe-broadhead/opencode-mem 0.9.12 → 0.11.2
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/CHANGELOG.md +1934 -2
- package/README.md +29 -17
- package/SECURITY.md +3 -1
- package/docs/agent-instructions.md +17 -0
- package/docs/agent-protocol.md +8 -8
- package/docs/permissions.md +22 -4
- package/package.json +7923 -217
- package/shared/page-paths.js +44 -0
- package/skills/mem.pages/SKILL.md +8 -1
- package/skills/mem.usage/SKILL.md +15 -15
- package/src/action-grant-keys.js +159 -0
- package/src/action-grant.js +439 -0
- package/src/actions.js +1690 -0
- package/src/backend/records.js +25 -2
- package/src/backend/v3.js +76 -22
- package/src/call-shapes.js +17 -16
- package/src/collector-lock.js +533 -62
- package/src/collector-service.js +153 -26
- package/src/collector.js +627 -33
- package/src/config.js +79 -6
- package/src/connect.js +106 -8
- package/src/credentials.js +123 -25
- package/src/events.js +174 -3
- package/src/forget-turn.js +141 -0
- package/src/host-refusal.js +78 -0
- package/src/index.js +209 -22
- package/src/jobs/host.js +557 -0
- package/src/ops/codes.js +110 -0
- package/src/ops/copy-lineage.js +42 -0
- package/src/ops/index.js +28 -0
- package/src/ops/space-ops.js +1936 -0
- package/src/outlinks.js +103 -0
- package/src/p2-reservation.js +151 -0
- package/src/permissions.js +30 -0
- package/src/plugins/descriptor.js +62 -0
- package/src/plugins/discovery.js +318 -0
- package/src/plugins/grants.js +178 -0
- package/src/plugins/locate.js +319 -0
- package/src/plugins/manifest.js +1162 -0
- package/src/plugins/source-contract/index.js +34 -0
- package/src/plugins/source-contract/policy.js +102 -0
- package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
- package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
- package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
- package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
- package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
- package/src/plugins/source-contract/vendor/broker-client.js +93 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/plugins/source-contract/vendor/cursor.js +26 -0
- package/src/plugins/source-contract/vendor/descriptor.js +34 -0
- package/src/plugins/source-contract/vendor/events.js +257 -0
- package/src/plugins/source-contract/vendor/index.js +10 -0
- package/src/plugins/source-contract/vendor/params.js +22 -0
- package/src/plugins/source-contract/vendor/permission.js +28 -0
- package/src/plugins/source-contract/vendor/pick.js +22 -0
- package/src/plugins/source-contract/vendor/read.js +29 -0
- package/src/plugins/source-contract/vendor/registry.js +23 -0
- package/src/plugins/source-contract/vendor/schema.js +17 -0
- package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
- package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
- package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
- package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
- package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
- package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
- package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
- package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
- package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
- package/src/plugins/source-contract/vendor/schemas.js +19 -0
- package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
- package/src/plugins/verify.js +56 -0
- package/src/protocol.js +21 -5
- package/src/recall.js +104 -5
- package/src/records.js +61 -2
- package/src/requests.js +216 -0
- package/src/runtime.js +89 -7
- package/src/setup-time.js +68 -0
- package/src/skills.js +230 -8
- package/src/source-ids.js +25 -0
- package/src/sources/declaration.js +365 -0
- package/src/sources/reads.js +772 -0
- package/src/sources/rpc.js +151 -0
- package/src/sources.js +409 -90
- package/src/spaces.js +283 -11
- package/src/spool.js +61 -4
- package/src/stated.js +10 -5
- package/src/storable.js +139 -0
- package/src/tools/commitments.js +47 -5
- package/src/tools/held-write.js +36 -13
- package/src/tools/index.js +27 -0
- package/src/tools/ingest.js +27 -2
- package/src/tools/memory.js +52 -14
- package/src/tools/page.js +95 -9
- package/src/tools/recall.js +208 -4
- package/src/tools/records-kit.js +2 -1
- package/src/tools/share.js +42 -3
- package/src/tools/shared.js +44 -4
- package/src/tools/space-lifecycle.js +278 -0
- package/src/tools/spaces.js +373 -29
- package/src/tools/status.js +9 -2
- package/src/tools/wiki.js +34 -4
- package/src/util.js +110 -6
- package/src/vendor/source-contract/README.md +24 -0
- package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
- package/src/vendor/source-contract/VENDOR.json +81 -0
- package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/vendor/source-contract/cursor.js +26 -0
- package/src/vendor/source-contract/events.js +257 -0
- package/src/vendor/source-contract/registry.js +23 -0
- package/src/vendor/source-contract/tools-rpc.js +42 -0
- package/src/views/access-reads.js +256 -0
- package/src/views/communities.js +77 -0
- package/src/views/contracts.js +1183 -36
- package/src/views/inbox-bytes.js +103 -0
- package/src/views/overdue.js +1 -1
- package/src/views/profile.js +31 -0
- package/src/views/receipt.js +81 -0
- package/src/views/records-reads.js +869 -37
- package/src/views/rpc.js +159 -11
- package/src/views/shape.js +8 -5
- package/views/memory.html +16 -3
- package/views/pages.html +2 -2
- package/views/remembered.html +130 -0
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
// @we-the-rebel-alliance/source-contract 0.1.0. Built by scripts/build.mjs; do not edit.
|
|
2
|
+
import {
|
|
3
|
+
MAX_CURSOR_LENGTH,
|
|
4
|
+
canonicalScope
|
|
5
|
+
} from "./chunk-I2RXJJJM.js";
|
|
6
|
+
|
|
7
|
+
// src/internal/secrets.ts
|
|
8
|
+
var PRIVATE_KEY_BLOCK = /-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?-----|$)/g;
|
|
9
|
+
var SHAPED = Object.freeze([
|
|
10
|
+
// At a word start, with a key-like tail: 20 or more key characters, letters and digits.
|
|
11
|
+
["api key", /(?<![A-Za-z0-9_-])sk-[A-Za-z0-9_-]{20,}/g, (match) => /\d/.test(match.slice(3)) && /[A-Za-z]/.test(match.slice(3))],
|
|
12
|
+
["api key", /\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g],
|
|
13
|
+
["api key", /\bAIza[0-9A-Za-z_-]{30,}/g],
|
|
14
|
+
["api key", /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g],
|
|
15
|
+
["api key", /\b(?:AccountKey|SharedAccessKey)=[A-Za-z0-9+/]{20,}={0,2}/g],
|
|
16
|
+
["token", /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{8,}/g],
|
|
17
|
+
["token", /\bgithub_pat_[A-Za-z0-9_]{20,}/g],
|
|
18
|
+
["token", /\bglpat-[A-Za-z0-9_-]{16,}/g],
|
|
19
|
+
["token", /\bxox[bpars]-[A-Za-z0-9-]{10,}/g],
|
|
20
|
+
["token", /\bnpm_[A-Za-z0-9]{30,}/g],
|
|
21
|
+
["token", /\bhf_[A-Za-z0-9]{30,}/g],
|
|
22
|
+
["token", /\bdop_v1_[A-Za-z0-9]{40,}/g],
|
|
23
|
+
["token", /https:\/\/hooks\.slack\.com\/(?:services|workflows|triggers)\/[A-Za-z0-9_/-]{20,}/g],
|
|
24
|
+
["token", /\beyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g]
|
|
25
|
+
]);
|
|
26
|
+
var BEARER = /\bBearer\s+([A-Za-z0-9._~+/=-]+)/gi;
|
|
27
|
+
var AUTH_HEADER = /\b(?:authorization|x-api-key)\b["']?\s*[:=]\s*(?:"([^"\n]*)"|'([^'\n]*)'|([^\s,;]+(?:[ \t]+[^\s,;]+)?))/gi;
|
|
28
|
+
var CONNECTION = /\b[a-z][a-z0-9+.-]*:\/\/([^\s:@/]+):([^\s/]*)@[^\s@/]+/gi;
|
|
29
|
+
var CREDENTIAL_KEYS = "api[_-]?key|apikey|access[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|client[_-]?secret|secret[_-]?key|private[_-]?key|passphrase|password|passwd|pwd|token|secret";
|
|
30
|
+
var ASSIGNMENT = new RegExp(
|
|
31
|
+
String.raw`(?<![A-Za-z0-9])([A-Za-z0-9_.-]*?(${CREDENTIAL_KEYS}))["']?((?:[ \t]+(?:is|was))?[ \t]*[:=][ \t]*(?:\r?\n[ \t]*)?)(?:"([^"\n]*)"|'([^'\n]*)'|` + "`([^`\\n]*)`" + String.raw`|([^\s,;&]+))`,
|
|
32
|
+
"gi"
|
|
33
|
+
);
|
|
34
|
+
var PLACEHOLDER = /^(?:\[[^\]]*\]|<[^>]*>|\{\{.*\}\}|\$\{?[A-Za-z_][\w.]*\}?|%[A-Za-z_]\w*%|\*+|x{3,}|\.{2,}|…|-+|true|false|null|nil|none|undefined|string|str|number|int|bool|required|optional|env|secret|password|token|redacted|placeholder|changeme|example|your[_-]?\w*|(?:process\.env|os\.environ|env)\b.*)$/i;
|
|
35
|
+
var JWT_IO_SAMPLE = /eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ|SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c/;
|
|
36
|
+
var TOKENISH = /^[A-Za-z0-9._~+/=!@#$%^&*()\-:]+$/;
|
|
37
|
+
function documentation(value) {
|
|
38
|
+
const v = String(value ?? "").trim();
|
|
39
|
+
return PLACEHOLDER.test(v) || /example/i.test(v) || /x{4,}/i.test(v) || /<[^>]*>/.test(v) || /\byour[-_][\w-]*here\b/i.test(v) || /\$\{|\{\{/.test(v) || JWT_IO_SAMPLE.test(v) || /[…]|\.{3}$/.test(v);
|
|
40
|
+
}
|
|
41
|
+
function codeValue(value) {
|
|
42
|
+
const v = String(value ?? "").trim();
|
|
43
|
+
return (
|
|
44
|
+
// `session.accessToken`, `config.secretKey`: identifiers, not a random token with digits in it.
|
|
45
|
+
/^[A-Za-z_$][\w$]*(?:\??\.[A-Za-z_$][\w$]*)+;?$/.test(v) && (v.match(/\d/g) ?? []).length <= 2 || /^(?:await\s+)?[A-Za-z_$][\w$.]*\(/.test(v) || /^(?:~|\.{1,2})?\/[\w./-]*$/.test(v) || /^(?:process\.env|os\.environ|import\.meta\.env)\b/.test(v)
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
function entropy(value) {
|
|
49
|
+
const counts = /* @__PURE__ */ new Map();
|
|
50
|
+
for (const char of value) counts.set(char, (counts.get(char) ?? 0) + 1);
|
|
51
|
+
let bits = 0;
|
|
52
|
+
for (const count of counts.values()) {
|
|
53
|
+
const p = count / value.length;
|
|
54
|
+
bits -= p * Math.log2(p);
|
|
55
|
+
}
|
|
56
|
+
return bits;
|
|
57
|
+
}
|
|
58
|
+
function tokenShaped(value, min = 12) {
|
|
59
|
+
const v = String(value ?? "").trim();
|
|
60
|
+
return v.length >= min && TOKENISH.test(v) && /\d/.test(v) && /[A-Za-z]/.test(v) && entropy(v) >= 3 && !documentation(v) && !codeValue(v);
|
|
61
|
+
}
|
|
62
|
+
var PROSE_WORDS = new Set(
|
|
63
|
+
"a an the is are was were be been must should shall will can may not no never always every each at least most of to in on for and or with by from via see use uses used set stored managed rotated rotate required policy characters chars minimum maximum change changed expires expire reset same as one this that it its".split(" ")
|
|
64
|
+
);
|
|
65
|
+
function passphrase(rest) {
|
|
66
|
+
const line2 = String(rest ?? "").trim();
|
|
67
|
+
if (line2.length < 16 || /[.!?]$/.test(line2)) return false;
|
|
68
|
+
const words = line2.split(/\s+/);
|
|
69
|
+
return words.length >= 3 && words.length <= 8 && words.every((word) => /^[A-Za-z][A-Za-z'-]*$/.test(word) && !PROSE_WORDS.has(word.toLowerCase()));
|
|
70
|
+
}
|
|
71
|
+
function credentialValue(value, quoted, key, query) {
|
|
72
|
+
const v = String(value ?? "").trim();
|
|
73
|
+
if (!v || documentation(v)) return false;
|
|
74
|
+
if (query) return tokenShaped(v, 16);
|
|
75
|
+
const loose = /^(?:token|secret)$/i.test(key);
|
|
76
|
+
if (quoted) return v.length >= (loose ? 8 : 4) && !/^\d+(?:\.\d+)?$/.test(v) && !/^[A-Za-z_$][\w$.]*\(|^\$\{/.test(v);
|
|
77
|
+
if (codeValue(v) || !TOKENISH.test(v) || /^\d+(?:\.\d+)?$/.test(v)) return false;
|
|
78
|
+
if (v.length < (loose ? 8 : 6)) return false;
|
|
79
|
+
return /\d/.test(v) || /[^A-Za-z0-9]/.test(v) || /.[A-Z]/.test(v);
|
|
80
|
+
}
|
|
81
|
+
function secretKinds(text2) {
|
|
82
|
+
const value = String(text2 ?? "");
|
|
83
|
+
const kinds = /* @__PURE__ */ new Set();
|
|
84
|
+
if (new RegExp(PRIVATE_KEY_BLOCK.source).test(value)) kinds.add("private key");
|
|
85
|
+
for (const [kind, pattern, valid] of SHAPED) {
|
|
86
|
+
for (const match of value.matchAll(pattern)) if (!documentation(match[0]) && (!valid || valid(match[0]))) kinds.add(kind);
|
|
87
|
+
}
|
|
88
|
+
for (const match of value.matchAll(BEARER)) if (tokenShaped(match[1])) kinds.add("token");
|
|
89
|
+
for (const match of value.matchAll(AUTH_HEADER)) {
|
|
90
|
+
const v = String(match[1] ?? match[2] ?? match[3] ?? "").trim().replace(/^(?:Bearer|Basic|Token|Bot)\s+/i, "");
|
|
91
|
+
if (tokenShaped(v)) kinds.add("token");
|
|
92
|
+
}
|
|
93
|
+
for (const match of value.matchAll(CONNECTION)) if (match[2].length >= 3 && !documentation(match[2])) kinds.add("connection string");
|
|
94
|
+
for (const match of value.matchAll(ASSIGNMENT)) {
|
|
95
|
+
const key = match[2];
|
|
96
|
+
const quoted = match[4] ?? match[5] ?? match[6];
|
|
97
|
+
const bare = match[7];
|
|
98
|
+
const crossed = /\n/.test(match[3]);
|
|
99
|
+
if (crossed && bare !== void 0 && /^[A-Za-z_][\w.-]*[:=]/.test(bare)) continue;
|
|
100
|
+
const query = /[?&]/.test(value[match.index - 1] ?? "");
|
|
101
|
+
const password = /pass|pwd/i.test(key);
|
|
102
|
+
let found = credentialValue(quoted ?? bare, quoted !== void 0, key, query);
|
|
103
|
+
if (!found && password && quoted === void 0 && !query) {
|
|
104
|
+
const start = match.index + match[0].length - (bare ?? "").length;
|
|
105
|
+
const end = value.indexOf("\n", start);
|
|
106
|
+
found = passphrase(value.slice(start, end === -1 ? value.length : end));
|
|
107
|
+
}
|
|
108
|
+
if (found) kinds.add(password ? "password" : /token/i.test(key) ? "token" : "api key");
|
|
109
|
+
}
|
|
110
|
+
return [...kinds];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// src/internal/events.ts
|
|
114
|
+
import { createHash } from "node:crypto";
|
|
115
|
+
var EVENTS_LIST = "events_list";
|
|
116
|
+
var EVENT_KINDS = ["message", "meeting", "session", "bookmark", "issue", "pr", "commit", "doc", "event", "task", "file"];
|
|
117
|
+
var EXTENSION_SEGMENT_MAX = 32;
|
|
118
|
+
var EXTENSION_NAME = new RegExp(`^x-[a-z][a-z0-9-]{0,${EXTENSION_SEGMENT_MAX - 1}}/[a-z][a-z0-9-]{0,${EXTENSION_SEGMENT_MAX - 1}}$`);
|
|
119
|
+
var EXTENSION_KIND = EXTENSION_NAME;
|
|
120
|
+
var isExtensionName = (name) => typeof name === "string" && EXTENSION_NAME.test(name);
|
|
121
|
+
var isEventKind = (kind) => typeof kind === "string" && (EVENT_KINDS.includes(kind) || isExtensionName(kind));
|
|
122
|
+
function extensionNamespace(kind) {
|
|
123
|
+
return isEventKind(kind) && kind.startsWith("x-") ? kind.slice(2, kind.indexOf("/")) : void 0;
|
|
124
|
+
}
|
|
125
|
+
function isEventKindIn(kind, namespace) {
|
|
126
|
+
if (!isEventKind(kind)) return false;
|
|
127
|
+
const own = extensionNamespace(kind);
|
|
128
|
+
return own === void 0 || own === namespace;
|
|
129
|
+
}
|
|
130
|
+
var sourceNamespace = (sourceId) => sourceId.split(".", 1)[0] ?? sourceId;
|
|
131
|
+
var EVENT_LIMITS = {
|
|
132
|
+
source: 64,
|
|
133
|
+
account: 128,
|
|
134
|
+
externalId: 512,
|
|
135
|
+
thread: 512,
|
|
136
|
+
title: 300,
|
|
137
|
+
text: 4096,
|
|
138
|
+
url: 2048,
|
|
139
|
+
actors: 20,
|
|
140
|
+
actorRole: 32,
|
|
141
|
+
actorId: 320,
|
|
142
|
+
actorName: 200,
|
|
143
|
+
labels: 20,
|
|
144
|
+
label: 64,
|
|
145
|
+
ownerId: 320,
|
|
146
|
+
ownerLabel: 200,
|
|
147
|
+
cursor: MAX_CURSOR_LENGTH,
|
|
148
|
+
scopeKeys: 16,
|
|
149
|
+
scopeKey: 64,
|
|
150
|
+
scopeValues: 64,
|
|
151
|
+
scopeValue: 256,
|
|
152
|
+
refused: 500,
|
|
153
|
+
failed: 500,
|
|
154
|
+
detail: 200,
|
|
155
|
+
costUnits: 8
|
|
156
|
+
};
|
|
157
|
+
var PAGE = { default: 100, min: 1, max: 500 };
|
|
158
|
+
var MAX_PAGE_BYTES = 65536;
|
|
159
|
+
var MAX_BYTES = { default: 65536, max: 1048576 };
|
|
160
|
+
var FIRST_RUN_HOURS = 24;
|
|
161
|
+
var TRUST = "untrusted";
|
|
162
|
+
var REFUSAL_REASONS = ["instruction", "secret", "owner"];
|
|
163
|
+
var GAP_REASONS = ["expired", "window-truncated"];
|
|
164
|
+
var ERROR_CODES = [
|
|
165
|
+
"NEEDS_SIGN_IN",
|
|
166
|
+
"ACCOUNT_MISMATCH",
|
|
167
|
+
"CURSOR_INVALID",
|
|
168
|
+
"CURSOR_EXPIRED",
|
|
169
|
+
"RATE_LIMITED",
|
|
170
|
+
"TOO_LARGE",
|
|
171
|
+
"SCHEMA_VIOLATION",
|
|
172
|
+
"PERMISSION_DENIED",
|
|
173
|
+
"UNAVAILABLE",
|
|
174
|
+
"SCOPE_MISSING",
|
|
175
|
+
"BUDGET_EXCEEDED",
|
|
176
|
+
"SOURCE_DISABLED",
|
|
177
|
+
"INPUT_INVALID",
|
|
178
|
+
"SOURCE_UNKNOWN"
|
|
179
|
+
];
|
|
180
|
+
var PROPOSED_CODES = [];
|
|
181
|
+
var ERROR_ALIASES = { AUTH_REQUIRED: "NEEDS_SIGN_IN" };
|
|
182
|
+
var CONTRACT1_CODES = {
|
|
183
|
+
EVENTS_INVALID_INPUT: "INPUT_INVALID",
|
|
184
|
+
EVENTS_CURSOR_INVALID: "CURSOR_INVALID",
|
|
185
|
+
EVENTS_SOURCE_UNKNOWN: "SOURCE_UNKNOWN"
|
|
186
|
+
};
|
|
187
|
+
function canonicalCode(code) {
|
|
188
|
+
if (ERROR_CODES.includes(code) || PROPOSED_CODES.includes(code)) return code;
|
|
189
|
+
return ERROR_ALIASES[code] ?? CONTRACT1_CODES[code];
|
|
190
|
+
}
|
|
191
|
+
var SourceError = class extends Error {
|
|
192
|
+
code;
|
|
193
|
+
what;
|
|
194
|
+
next;
|
|
195
|
+
retryAfterSec;
|
|
196
|
+
gap;
|
|
197
|
+
constructor(init) {
|
|
198
|
+
super(`${init.code}: ${init.what.replace(/[.\s]+$/, "")}. Next step: ${init.next}`);
|
|
199
|
+
this.name = "SourceError";
|
|
200
|
+
this.code = init.code;
|
|
201
|
+
this.what = init.what;
|
|
202
|
+
this.next = init.next;
|
|
203
|
+
if (init.retryAfterSec !== void 0) this.retryAfterSec = init.retryAfterSec;
|
|
204
|
+
if (init.gap !== void 0) this.gap = init.gap;
|
|
205
|
+
}
|
|
206
|
+
};
|
|
207
|
+
var FAMILY_MESSAGE = /^([A-Z][A-Z0-9_]*): ([^]*?)(?:\. Next step: ([^]*))?$/;
|
|
208
|
+
function parseSourceError(error) {
|
|
209
|
+
if (error instanceof SourceError) {
|
|
210
|
+
const canonical2 = canonicalCode(error.code);
|
|
211
|
+
return { code: error.code, ...canonical2 ? { canonical: canonical2 } : {}, what: error.what, next: error.next };
|
|
212
|
+
}
|
|
213
|
+
const message = error instanceof Error ? error.message : typeof error === "string" ? error : void 0;
|
|
214
|
+
const match = message === void 0 ? null : FAMILY_MESSAGE.exec(message.split("\n", 1)[0] ?? "");
|
|
215
|
+
if (!match) return void 0;
|
|
216
|
+
const canonical = canonicalCode(match[1]);
|
|
217
|
+
return { code: match[1], ...canonical ? { canonical } : {}, what: match[2], ...match[3] === void 0 ? {} : { next: match[3] } };
|
|
218
|
+
}
|
|
219
|
+
var SINCE_PATTERN = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?(?:Z|[+-]\d{2}:\d{2}))?$/;
|
|
220
|
+
var SOURCE_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
221
|
+
var SCOPE_KEY_PATTERN = /^[a-z][A-Za-z0-9_-]*$/;
|
|
222
|
+
var INPUT_KEYS = ["since", "cursor", "limit", "account", "source"];
|
|
223
|
+
var hasControl = (text2) => [...text2].some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127);
|
|
224
|
+
var plainObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
225
|
+
function sinceTime(since) {
|
|
226
|
+
if (!SINCE_PATTERN.test(since)) return void 0;
|
|
227
|
+
const time = Date.parse(since.length === 10 ? `${since}T00:00:00Z` : since);
|
|
228
|
+
return Number.isFinite(time) ? time : void 0;
|
|
229
|
+
}
|
|
230
|
+
var scopeValue = (value) => typeof value === "string" && value.length > 0 && value.length <= EVENT_LIMITS.scopeValue && !hasControl(value);
|
|
231
|
+
function scopeProblems(scope, keys) {
|
|
232
|
+
if (!plainObject(scope)) return [`"scope" must be an object of the source's scope keys`];
|
|
233
|
+
const problems = [];
|
|
234
|
+
const entries = Object.entries(scope);
|
|
235
|
+
if (entries.length > EVENT_LIMITS.scopeKeys) problems.push(`"scope" has more than ${EVENT_LIMITS.scopeKeys} keys`);
|
|
236
|
+
for (const [key, value] of entries) {
|
|
237
|
+
if (!keys.includes(key)) {
|
|
238
|
+
problems.push(SCOPE_KEY_PATTERN.test(key) && key.length <= EVENT_LIMITS.scopeKey ? `"scope.${key}" is not a scope key of this source` : `"scope" has a key that is not a scope key of this source`);
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
const ok = scopeValue(value) || Array.isArray(value) && value.length <= EVENT_LIMITS.scopeValues && value.every(scopeValue);
|
|
242
|
+
if (!ok) problems.push(`"scope.${key}" must be a value, or a list of at most ${EVENT_LIMITS.scopeValues} values, of at most ${EVENT_LIMITS.scopeValue} characters`);
|
|
243
|
+
}
|
|
244
|
+
return problems;
|
|
245
|
+
}
|
|
246
|
+
function parseEventsListInput(input, options = {}) {
|
|
247
|
+
const value = input === void 0 || input === null ? {} : input;
|
|
248
|
+
if (!plainObject(value)) return { ok: false, problems: ["the input must be an object"] };
|
|
249
|
+
const scoped = (options.scopeKeys?.length ?? 0) > 0;
|
|
250
|
+
const known = scoped ? [...INPUT_KEYS, "scope"] : INPUT_KEYS;
|
|
251
|
+
const problems = Object.keys(value).filter((key) => !known.includes(key)).map((key) => `"${key}" is not an input of events_list`);
|
|
252
|
+
const { since, cursor, limit, account, source, scope } = value;
|
|
253
|
+
let time;
|
|
254
|
+
if (since !== void 0) {
|
|
255
|
+
time = typeof since === "string" ? sinceTime(since) : void 0;
|
|
256
|
+
if (time === void 0) problems.push(`"since" must be an ISO date, or an ISO date-time with Z or an offset`);
|
|
257
|
+
}
|
|
258
|
+
if (cursor !== void 0 && (typeof cursor !== "string" || cursor.length === 0 || cursor.length > EVENT_LIMITS.cursor)) {
|
|
259
|
+
problems.push(`"cursor" must be a cursor from a previous result`);
|
|
260
|
+
}
|
|
261
|
+
if (limit !== void 0 && (typeof limit !== "number" || !Number.isInteger(limit) || limit < PAGE.min || limit > PAGE.max)) {
|
|
262
|
+
problems.push(`"limit" must be an integer from ${PAGE.min} to ${PAGE.max}`);
|
|
263
|
+
}
|
|
264
|
+
if (account !== void 0 && (typeof account !== "string" || account.length === 0 || account.length > EVENT_LIMITS.account || hasControl(account))) {
|
|
265
|
+
problems.push(`"account" must be a non-empty account name of at most ${EVENT_LIMITS.account} characters`);
|
|
266
|
+
}
|
|
267
|
+
if (source !== void 0 && (typeof source !== "string" || source.length > EVENT_LIMITS.source || !SOURCE_PATTERN.test(source))) {
|
|
268
|
+
problems.push(`"source" must be a source's name, a lowercase word such as gmail`);
|
|
269
|
+
}
|
|
270
|
+
if (scoped && scope !== void 0) problems.push(...scopeProblems(scope, options.scopeKeys));
|
|
271
|
+
if (problems.length > 0) return { ok: false, problems };
|
|
272
|
+
return {
|
|
273
|
+
ok: true,
|
|
274
|
+
value: {
|
|
275
|
+
...time === void 0 ? {} : { since: time },
|
|
276
|
+
...cursor === void 0 ? {} : { cursor },
|
|
277
|
+
limit: limit ?? PAGE.default,
|
|
278
|
+
...account === void 0 ? {} : { account },
|
|
279
|
+
...source === void 0 ? {} : { source },
|
|
280
|
+
...scoped && scope !== void 0 ? { scope: canonicalScope(scope) } : {}
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
function startTime(request, now) {
|
|
285
|
+
return request.since ?? now - FIRST_RUN_HOURS * 36e5;
|
|
286
|
+
}
|
|
287
|
+
function cut(text2, max) {
|
|
288
|
+
if (text2.length <= max) return text2;
|
|
289
|
+
let end = Math.max(0, max - 1);
|
|
290
|
+
const code = text2.charCodeAt(end - 1);
|
|
291
|
+
if (end > 0 && code >= 55296 && code <= 56319) end--;
|
|
292
|
+
return `${text2.slice(0, end)}\u2026`;
|
|
293
|
+
}
|
|
294
|
+
function eventHash(event) {
|
|
295
|
+
const fields = [
|
|
296
|
+
event.source,
|
|
297
|
+
event.account,
|
|
298
|
+
event.external_id,
|
|
299
|
+
event.kind,
|
|
300
|
+
event.occurred_at,
|
|
301
|
+
event.thread,
|
|
302
|
+
event.actors.map((actor) => [actor.role, actor.id, actor.name ?? null]),
|
|
303
|
+
event.title,
|
|
304
|
+
event.text,
|
|
305
|
+
event.url,
|
|
306
|
+
event.labels
|
|
307
|
+
];
|
|
308
|
+
return `sha256:${createHash("sha256").update(JSON.stringify(fields)).digest("hex")}`;
|
|
309
|
+
}
|
|
310
|
+
var clean = (text2) => text2.replaceAll("\0", "");
|
|
311
|
+
var oneLine = (text2) => clean(text2).replace(/\s+/g, " ").trim();
|
|
312
|
+
function makeEvent(draft) {
|
|
313
|
+
const time = draft.occurred_at instanceof Date ? draft.occurred_at.getTime() : typeof draft.occurred_at === "number" ? draft.occurred_at : Date.parse(draft.occurred_at);
|
|
314
|
+
if (!Number.isFinite(time)) throw new Error("events-list: an event's occurred_at is not a time");
|
|
315
|
+
const seen = /* @__PURE__ */ new Set();
|
|
316
|
+
const actors = [];
|
|
317
|
+
for (const actor of draft.actors ?? []) {
|
|
318
|
+
const role = oneLine(actor.role).toLowerCase();
|
|
319
|
+
const id = oneLine(actor.id);
|
|
320
|
+
const key = `${role}\0${id}`;
|
|
321
|
+
if (!role || !id || seen.has(key) || actors.length >= EVENT_LIMITS.actors) continue;
|
|
322
|
+
seen.add(key);
|
|
323
|
+
const name = actor.name ? cut(oneLine(actor.name), EVENT_LIMITS.actorName) : "";
|
|
324
|
+
actors.push(name ? { role, id, name } : { role, id });
|
|
325
|
+
}
|
|
326
|
+
const labels = [...new Set((draft.labels ?? []).map((label) => oneLine(label).replace(/\s/g, "-")).filter((label) => label.length > 0 && label.length <= EVENT_LIMITS.label))].slice(0, EVENT_LIMITS.labels);
|
|
327
|
+
const url = draft.url && /^https:\/\/\S+$/.test(draft.url) && draft.url.length <= EVENT_LIMITS.url ? draft.url : null;
|
|
328
|
+
const thread = draft.thread ? oneLine(draft.thread) || null : null;
|
|
329
|
+
const event = {
|
|
330
|
+
source: draft.source,
|
|
331
|
+
account: draft.account,
|
|
332
|
+
external_id: draft.external_id,
|
|
333
|
+
kind: draft.kind,
|
|
334
|
+
occurred_at: new Date(time).toISOString(),
|
|
335
|
+
thread,
|
|
336
|
+
actors,
|
|
337
|
+
title: cut(oneLine(draft.title ?? ""), EVENT_LIMITS.title),
|
|
338
|
+
text: cut(clean(draft.text ?? "").trim(), EVENT_LIMITS.text),
|
|
339
|
+
url,
|
|
340
|
+
labels
|
|
341
|
+
};
|
|
342
|
+
return { ...event, hash: eventHash(event) };
|
|
343
|
+
}
|
|
344
|
+
function oldestFirst(events) {
|
|
345
|
+
return events.map((event, index) => ({ event, index, time: Date.parse(event.occurred_at) })).sort((a, b) => a.time - b.time || a.index - b.index).map(({ event }) => event);
|
|
346
|
+
}
|
|
347
|
+
function fitPage(events, limit, maxBytes = MAX_PAGE_BYTES) {
|
|
348
|
+
let bytes = 2048;
|
|
349
|
+
let count = 0;
|
|
350
|
+
for (const event of events) {
|
|
351
|
+
if (count >= limit) break;
|
|
352
|
+
bytes += Buffer.byteLength(JSON.stringify(event)) + 1;
|
|
353
|
+
if (count > 0 && bytes > maxBytes) break;
|
|
354
|
+
count++;
|
|
355
|
+
}
|
|
356
|
+
return count;
|
|
357
|
+
}
|
|
358
|
+
function screenEvents(events, options = {}) {
|
|
359
|
+
const detect = options.secrets ?? secretKinds;
|
|
360
|
+
const kept = [];
|
|
361
|
+
const refused = [];
|
|
362
|
+
for (const event of events) {
|
|
363
|
+
if (options.ownedBy && !options.ownedBy(event)) {
|
|
364
|
+
refused.push({ external_id: event.external_id, reason: "owner" });
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
const kinds = detect([event.title, event.text].filter(Boolean).join("\n"));
|
|
368
|
+
if (kinds.length > 0) {
|
|
369
|
+
refused.push({ external_id: event.external_id, reason: "secret", detail: cut(`holds a secret (${kinds.join(", ")})`, EVENT_LIMITS.detail) });
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (options.instruction?.(event)) {
|
|
373
|
+
refused.push({ external_id: event.external_id, reason: "instruction" });
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
kept.push(event);
|
|
377
|
+
}
|
|
378
|
+
return { events: kept, refused };
|
|
379
|
+
}
|
|
380
|
+
var PROBE = "probe";
|
|
381
|
+
var PROBE_LIMITS = { scopes: 64, scope: 256 };
|
|
382
|
+
function parseProbeInput(input) {
|
|
383
|
+
const value = input === void 0 || input === null ? {} : input;
|
|
384
|
+
if (!plainObject(value)) return { ok: false, problems: ["the input must be an object"] };
|
|
385
|
+
const problems = Object.keys(value).filter((key) => key !== "source" && key !== "account").map((key) => `"${key}" is not an input of probe`);
|
|
386
|
+
const { source, account } = value;
|
|
387
|
+
if (source !== void 0 && (typeof source !== "string" || source.length > EVENT_LIMITS.source || !SOURCE_PATTERN.test(source))) {
|
|
388
|
+
problems.push(`"source" must be a source's name, a lowercase word such as gmail`);
|
|
389
|
+
}
|
|
390
|
+
if (account !== void 0 && (typeof account !== "string" || account.length === 0 || account.length > EVENT_LIMITS.account || hasControl(account))) {
|
|
391
|
+
problems.push(`"account" must be a non-empty account name of at most ${EVENT_LIMITS.account} characters`);
|
|
392
|
+
}
|
|
393
|
+
if (problems.length > 0) return { ok: false, problems };
|
|
394
|
+
return { ok: true, value: { ...source === void 0 ? {} : { source }, ...account === void 0 ? {} : { account } } };
|
|
395
|
+
}
|
|
396
|
+
function probeResult(identity, extras = {}) {
|
|
397
|
+
return {
|
|
398
|
+
source: identity.source,
|
|
399
|
+
account: identity.account,
|
|
400
|
+
owner: { id: identity.owner.id, label: identity.owner.label },
|
|
401
|
+
...extras.scopes === void 0 ? {} : { scopes: [...new Set(extras.scopes)] },
|
|
402
|
+
...extras.cost === void 0 ? {} : { cost: extras.cost },
|
|
403
|
+
trust: TRUST
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
var PROBE_KEYS = ["source", "account", "owner", "scopes", "cost", "trust"];
|
|
407
|
+
function probeResultProblems(result, expected = {}) {
|
|
408
|
+
if (!plainObject(result)) return ["the probe answer is not an object"];
|
|
409
|
+
const problems = [];
|
|
410
|
+
for (const key of Object.keys(result)) if (!PROBE_KEYS.includes(key)) problems.push(`the probe answer has the field "${key}": a probe reads no content, and the contract defines no such field`);
|
|
411
|
+
if (!line(result["source"], EVENT_LIMITS.source) || !SOURCE_PATTERN.test(result["source"])) problems.push("the probe answer's source must be a lowercase name such as gmail");
|
|
412
|
+
else if (expected.source !== void 0 && result["source"] !== expected.source) problems.push(`the probe answer names the source ${result["source"]}, not ${expected.source}`);
|
|
413
|
+
if (!line(result["account"], EVENT_LIMITS.account)) problems.push(`the probe answer's account must be a non-empty name of at most ${EVENT_LIMITS.account} characters`);
|
|
414
|
+
else if (expected.account !== void 0 && result["account"] !== expected.account) problems.push("the probe answer names another account than the one asked for");
|
|
415
|
+
const owner = result["owner"];
|
|
416
|
+
if (!plainObject(owner) || !line(owner["id"], EVENT_LIMITS.ownerId) || !line(owner["label"], EVENT_LIMITS.ownerLabel) || Object.keys(owner).some((key) => key !== "id" && key !== "label")) {
|
|
417
|
+
problems.push("the probe answer's owner must be { id, label }, two non-empty lines");
|
|
418
|
+
}
|
|
419
|
+
const scopes = result["scopes"];
|
|
420
|
+
if (scopes !== void 0 && (!Array.isArray(scopes) || scopes.length > PROBE_LIMITS.scopes || scopes.some((scope) => !line(scope, PROBE_LIMITS.scope)) || new Set(scopes).size !== scopes.length)) {
|
|
421
|
+
problems.push(`the probe answer's scopes must be at most ${PROBE_LIMITS.scopes} different lines of at most ${PROBE_LIMITS.scope} characters`);
|
|
422
|
+
}
|
|
423
|
+
if (result["cost"] !== void 0) problems.push(...extraProblems({ cost: result["cost"] }, /* @__PURE__ */ new Set()).map((problem) => problem.replace("the result's cost", "the probe answer's cost")));
|
|
424
|
+
if (result["trust"] !== TRUST) problems.push(`the probe answer's trust must be "${TRUST}"`);
|
|
425
|
+
return problems;
|
|
426
|
+
}
|
|
427
|
+
function eventsListResult(identity, events, cursor, more, extras = {}) {
|
|
428
|
+
return {
|
|
429
|
+
source: identity.source,
|
|
430
|
+
account: identity.account,
|
|
431
|
+
owner: identity.owner,
|
|
432
|
+
events: [...events],
|
|
433
|
+
cursor,
|
|
434
|
+
more,
|
|
435
|
+
trust: TRUST,
|
|
436
|
+
...extras.scope === void 0 ? {} : { scope: canonicalScope(extras.scope) },
|
|
437
|
+
...extras.refused && extras.refused.length > 0 ? { refused: [...extras.refused] } : {},
|
|
438
|
+
...extras.failed && extras.failed.length > 0 ? { failed: [...extras.failed] } : {},
|
|
439
|
+
...extras.gap === void 0 ? {} : { gap: extras.gap },
|
|
440
|
+
...extras.cost === void 0 ? {} : { cost: extras.cost },
|
|
441
|
+
...extras.plugin === void 0 ? {} : { plugin: extras.plugin },
|
|
442
|
+
...extras.asOf === void 0 ? {} : { asOf: extras.asOf }
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
var ISO_UTC = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/;
|
|
446
|
+
var ROLE = /^[a-z][a-z0-9_-]*$/;
|
|
447
|
+
var SCHEMED = /^[a-z][a-z0-9+.-]*:\S+$/;
|
|
448
|
+
var HASH = /^sha256:[0-9a-f]{64}$/;
|
|
449
|
+
var CODE = /^[A-Z][A-Z0-9_]*$/;
|
|
450
|
+
var UNIT = /^[a-z][a-z0-9_-]*$/;
|
|
451
|
+
var text = (value, max, empty = false) => typeof value === "string" && value.length <= max && (empty || value.length > 0) && !value.includes("\0");
|
|
452
|
+
var line = (value, max, empty = false) => text(value, max, empty) && !hasControl(value);
|
|
453
|
+
var isoUtc = (value) => typeof value === "string" && ISO_UTC.test(value) && Number.isFinite(Date.parse(value));
|
|
454
|
+
function eventProblems(event, where = "event") {
|
|
455
|
+
if (!plainObject(event)) return [`${where} is not an object`];
|
|
456
|
+
const problems = [];
|
|
457
|
+
const keys = ["source", "account", "external_id", "kind", "occurred_at", "thread", "actors", "title", "text", "url", "labels", "hash"];
|
|
458
|
+
for (const key of Object.keys(event)) if (!keys.includes(key)) problems.push(`${where} has the field "${key}", which the contract does not define`);
|
|
459
|
+
for (const key of keys) if (!Object.hasOwn(event, key)) problems.push(`${where} has no "${key}"`);
|
|
460
|
+
const e = event;
|
|
461
|
+
if (!line(e.source, EVENT_LIMITS.source) || !SOURCE_PATTERN.test(e.source)) problems.push(`${where}.source must be a lowercase name such as gmail`);
|
|
462
|
+
if (!line(e.account, EVENT_LIMITS.account)) problems.push(`${where}.account must be a non-empty name of at most ${EVENT_LIMITS.account} characters`);
|
|
463
|
+
if (!line(e.external_id, EVENT_LIMITS.externalId)) problems.push(`${where}.external_id must be a non-empty id of at most ${EVENT_LIMITS.externalId} characters`);
|
|
464
|
+
if (!isEventKind(e.kind)) problems.push(`${where}.kind must be one of ${EVENT_KINDS.join(", ")}, or x-<plugin>/<kind>`);
|
|
465
|
+
if (!isoUtc(e.occurred_at)) problems.push(`${where}.occurred_at must be a UTC ISO date-time ending in Z`);
|
|
466
|
+
if (e.thread !== null && !line(e.thread, EVENT_LIMITS.thread)) problems.push(`${where}.thread must be null or a non-empty id of at most ${EVENT_LIMITS.thread} characters`);
|
|
467
|
+
if (!line(e.title, EVENT_LIMITS.title, true)) problems.push(`${where}.title must be one line of at most ${EVENT_LIMITS.title} characters`);
|
|
468
|
+
if (!text(e.text, EVENT_LIMITS.text, true)) problems.push(`${where}.text must be at most ${EVENT_LIMITS.text} characters`);
|
|
469
|
+
if (e.url !== null && (typeof e.url !== "string" || e.url.length > EVENT_LIMITS.url || !/^https:\/\/\S+$/.test(e.url))) problems.push(`${where}.url must be null or an https URL`);
|
|
470
|
+
if (!Array.isArray(e.labels) || e.labels.length > EVENT_LIMITS.labels || e.labels.some((label) => !line(label, EVENT_LIMITS.label) || /\s/.test(label))) {
|
|
471
|
+
problems.push(`${where}.labels must be at most ${EVENT_LIMITS.labels} labels of at most ${EVENT_LIMITS.label} characters without spaces`);
|
|
472
|
+
} else if (new Set(e.labels).size !== e.labels.length) problems.push(`${where}.labels repeats a label`);
|
|
473
|
+
if (!Array.isArray(e.actors) || e.actors.length > EVENT_LIMITS.actors) problems.push(`${where}.actors must be a list of at most ${EVENT_LIMITS.actors}`);
|
|
474
|
+
else {
|
|
475
|
+
const seen = /* @__PURE__ */ new Set();
|
|
476
|
+
for (const [index, actor] of e.actors.entries()) {
|
|
477
|
+
const at = `${where}.actors[${index}]`;
|
|
478
|
+
if (!plainObject(actor)) {
|
|
479
|
+
problems.push(`${at} is not an object`);
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
for (const key2 of Object.keys(actor)) if (!["role", "id", "name"].includes(key2)) problems.push(`${at} has the field "${key2}", which the contract does not define`);
|
|
483
|
+
if (!line(actor.role, EVENT_LIMITS.actorRole) || !ROLE.test(actor.role)) problems.push(`${at}.role must be a lowercase word such as from`);
|
|
484
|
+
if (!line(actor.id, EVENT_LIMITS.actorId) || !SCHEMED.test(actor.id)) problems.push(`${at}.id must be a scheme-qualified id such as mailto:someone@example.com`);
|
|
485
|
+
if (actor.name !== void 0 && !line(actor.name, EVENT_LIMITS.actorName)) problems.push(`${at}.name must be one non-empty line of at most ${EVENT_LIMITS.actorName} characters`);
|
|
486
|
+
const key = `${String(actor.role)}\0${String(actor.id)}`;
|
|
487
|
+
if (seen.has(key)) problems.push(`${at} repeats an actor`);
|
|
488
|
+
seen.add(key);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
if (typeof e.hash !== "string" || !HASH.test(e.hash)) problems.push(`${where}.hash must be sha256: and 64 hex digits`);
|
|
492
|
+
else if (problems.length === 0) {
|
|
493
|
+
const { hash, ...rest } = e;
|
|
494
|
+
if (eventHash(rest) !== hash) problems.push(`${where}.hash is not the eventHash of its fields`);
|
|
495
|
+
}
|
|
496
|
+
return problems;
|
|
497
|
+
}
|
|
498
|
+
var RESULT_KEYS = ["source", "account", "owner", "events", "cursor", "more", "trust"];
|
|
499
|
+
var EXTRA_KEYS = ["scope", "refused", "failed", "gap", "cost", "plugin", "asOf"];
|
|
500
|
+
function extraProblems(result, ids) {
|
|
501
|
+
const problems = [];
|
|
502
|
+
if (result["scope"] !== void 0) {
|
|
503
|
+
const scope = result["scope"];
|
|
504
|
+
let canonical = false;
|
|
505
|
+
try {
|
|
506
|
+
canonical = plainObject(scope) && JSON.stringify(canonicalScope(scope)) === JSON.stringify(scope);
|
|
507
|
+
} catch {
|
|
508
|
+
canonical = false;
|
|
509
|
+
}
|
|
510
|
+
if (!canonical || scopeProblems(scope, Object.keys(scope)).length > 0) problems.push("the result's scope must be a scope in canonical form: keys sorted, each list sorted without repeats");
|
|
511
|
+
}
|
|
512
|
+
const entries = (name, max, check) => {
|
|
513
|
+
const list = result[name];
|
|
514
|
+
if (list === void 0) return;
|
|
515
|
+
if (!Array.isArray(list) || list.length > max) {
|
|
516
|
+
problems.push(`the result's ${name} must be a list of at most ${max}`);
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
for (const [index, entry] of list.entries()) {
|
|
520
|
+
const at = `${name}[${index}]`;
|
|
521
|
+
if (!plainObject(entry)) {
|
|
522
|
+
problems.push(`${at} is not an object`);
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (!line(entry["external_id"], EVENT_LIMITS.externalId)) problems.push(`${at}.external_id must be a non-empty id of at most ${EVENT_LIMITS.externalId} characters`);
|
|
526
|
+
else if (ids.has(entry["external_id"])) problems.push(`${at} is also among the result's events`);
|
|
527
|
+
problems.push(...check(entry, at));
|
|
528
|
+
}
|
|
529
|
+
};
|
|
530
|
+
entries("refused", EVENT_LIMITS.refused, (entry, at) => [
|
|
531
|
+
...Object.keys(entry).filter((key) => !["external_id", "reason", "detail"].includes(key)).map((key) => `${at} has the field "${key}", which the contract does not define`),
|
|
532
|
+
...REFUSAL_REASONS.includes(entry["reason"]) ? [] : [`${at}.reason must be one of ${REFUSAL_REASONS.join(", ")}`],
|
|
533
|
+
...entry["detail"] === void 0 || line(entry["detail"], EVENT_LIMITS.detail) ? [] : [`${at}.detail must be one line of at most ${EVENT_LIMITS.detail} characters`]
|
|
534
|
+
]);
|
|
535
|
+
entries("failed", EVENT_LIMITS.failed, (entry, at) => [
|
|
536
|
+
...Object.keys(entry).filter((key) => !["external_id", "code", "retryAfterSec"].includes(key)).map((key) => `${at} has the field "${key}", which the contract does not define`),
|
|
537
|
+
...typeof entry["code"] === "string" && CODE.test(entry["code"]) ? [] : [`${at}.code must be an error code such as RATE_LIMITED`],
|
|
538
|
+
...entry["retryAfterSec"] === void 0 || typeof entry["retryAfterSec"] === "number" && Number.isInteger(entry["retryAfterSec"]) && entry["retryAfterSec"] >= 0 ? [] : [`${at}.retryAfterSec must be a whole number of seconds`]
|
|
539
|
+
]);
|
|
540
|
+
for (const name of ["refused", "failed"]) {
|
|
541
|
+
const list = result[name];
|
|
542
|
+
if (Array.isArray(list)) {
|
|
543
|
+
const listed = list.map((entry) => plainObject(entry) ? entry["external_id"] : void 0);
|
|
544
|
+
if (new Set(listed).size !== listed.length) problems.push(`the result's ${name} lists one event twice`);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
if (Array.isArray(result["refused"]) && Array.isArray(result["failed"])) {
|
|
548
|
+
const refused = new Set(result["refused"].map((entry) => plainObject(entry) ? entry["external_id"] : void 0));
|
|
549
|
+
if (result["failed"].some((entry) => plainObject(entry) && refused.has(entry["external_id"]))) problems.push("an event is both refused and failed");
|
|
550
|
+
}
|
|
551
|
+
if (result["gap"] !== void 0) {
|
|
552
|
+
const gap = result["gap"];
|
|
553
|
+
if (!plainObject(gap) || Object.keys(gap).some((key) => key !== "reason" && key !== "since") || !GAP_REASONS.includes(gap["reason"]) || !isoUtc(gap["since"])) {
|
|
554
|
+
problems.push(`the result's gap must be { reason: ${GAP_REASONS.join(" or ")}, since: a UTC ISO date-time }`);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
if (result["cost"] !== void 0) {
|
|
558
|
+
const cost = result["cost"];
|
|
559
|
+
const units = plainObject(cost) ? cost["units"] : void 0;
|
|
560
|
+
const unitsOk = Array.isArray(units) && units.length <= EVENT_LIMITS.costUnits && units.every((unit) => plainObject(unit) && Object.keys(unit).every((key) => key === "per" || key === "count") && typeof unit["per"] === "string" && UNIT.test(unit["per"]) && typeof unit["count"] === "number" && Number.isInteger(unit["count"]) && unit["count"] >= 0);
|
|
561
|
+
const usd = plainObject(cost) ? cost["usd"] : void 0;
|
|
562
|
+
const usdOk = usd === void 0 || typeof usd === "number" && Number.isFinite(usd) && usd >= 0;
|
|
563
|
+
if (!plainObject(cost) || Object.keys(cost).some((key) => key !== "units" && key !== "usd") || !unitsOk || !usdOk) {
|
|
564
|
+
problems.push("the result's cost must be { units: [{ per, count }], usd? }, with whole counts and a non-negative usd");
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
if (result["plugin"] !== void 0 && !line(result["plugin"], 214)) problems.push("the result's plugin must be the plugin's package name or id");
|
|
568
|
+
if (result["asOf"] !== void 0 && !isoUtc(result["asOf"])) problems.push("the result's asOf must be a UTC ISO date-time ending in Z");
|
|
569
|
+
return problems;
|
|
570
|
+
}
|
|
571
|
+
function resultProblems(result, limit = PAGE.max, maxBytes = MAX_PAGE_BYTES) {
|
|
572
|
+
if (!plainObject(result)) return ["the result is not an object"];
|
|
573
|
+
const problems = [];
|
|
574
|
+
for (const key of Object.keys(result)) if (!RESULT_KEYS.includes(key) && !EXTRA_KEYS.includes(key)) problems.push(`the result has the field "${key}", which the contract does not define`);
|
|
575
|
+
const { source, account } = result;
|
|
576
|
+
const named = line(source, EVENT_LIMITS.source) && SOURCE_PATTERN.test(source);
|
|
577
|
+
if (!named) problems.push("the result's source must be a lowercase name such as gmail");
|
|
578
|
+
if (!line(account, EVENT_LIMITS.account)) problems.push(`the result's account must be a non-empty name of at most ${EVENT_LIMITS.account} characters`);
|
|
579
|
+
const owner = result["owner"];
|
|
580
|
+
if (!plainObject(owner) || !line(owner["id"], EVENT_LIMITS.ownerId) || !line(owner["label"], EVENT_LIMITS.ownerLabel) || Object.keys(owner).some((key) => key !== "id" && key !== "label")) {
|
|
581
|
+
problems.push("the result's owner must be { id, label }, two non-empty lines");
|
|
582
|
+
}
|
|
583
|
+
const cursor = result["cursor"];
|
|
584
|
+
if (typeof cursor !== "string" || cursor.length === 0 || cursor.length > EVENT_LIMITS.cursor) problems.push(`the result's cursor must be a non-empty string of at most ${EVENT_LIMITS.cursor} characters`);
|
|
585
|
+
if (typeof result["more"] !== "boolean") problems.push("the result's more must be true or false");
|
|
586
|
+
if (result["trust"] !== TRUST) problems.push(`the result's trust must be "${TRUST}"`);
|
|
587
|
+
const events = result["events"];
|
|
588
|
+
if (!Array.isArray(events)) return [...problems, "the result's events must be a list"];
|
|
589
|
+
if (events.length > limit) problems.push(`the result has ${events.length} events, over the limit of ${limit}`);
|
|
590
|
+
for (const [index, event] of events.entries()) {
|
|
591
|
+
problems.push(...eventProblems(event, `events[${index}]`));
|
|
592
|
+
if (plainObject(event) && named && event["source"] !== source) problems.push(`events[${index}] names another source than the result`);
|
|
593
|
+
if (plainObject(event) && typeof account === "string" && event["account"] !== account) problems.push(`events[${index}] names another account than the result`);
|
|
594
|
+
}
|
|
595
|
+
const times = events.map((event) => Date.parse(plainObject(event) ? String(event["occurred_at"]) : ""));
|
|
596
|
+
if (times.some((time, index) => index > 0 && time < times[index - 1])) problems.push("the result's events are not oldest first");
|
|
597
|
+
const ids = events.map((event) => plainObject(event) ? `${String(event["source"])}:${String(event["account"])}:${String(event["external_id"])}` : "");
|
|
598
|
+
if (new Set(ids).size !== ids.length) problems.push("the result lists one event twice");
|
|
599
|
+
problems.push(...extraProblems(result, new Set(events.map((event) => plainObject(event) ? String(event["external_id"]) : ""))));
|
|
600
|
+
const bytes = Buffer.byteLength(JSON.stringify(result));
|
|
601
|
+
if (bytes > maxBytes) problems.push(`the result is ${bytes} bytes of JSON, over ${maxBytes}`);
|
|
602
|
+
return problems;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
export {
|
|
606
|
+
secretKinds,
|
|
607
|
+
EVENTS_LIST,
|
|
608
|
+
EVENT_KINDS,
|
|
609
|
+
EXTENSION_SEGMENT_MAX,
|
|
610
|
+
EXTENSION_NAME,
|
|
611
|
+
EXTENSION_KIND,
|
|
612
|
+
isExtensionName,
|
|
613
|
+
isEventKind,
|
|
614
|
+
extensionNamespace,
|
|
615
|
+
isEventKindIn,
|
|
616
|
+
sourceNamespace,
|
|
617
|
+
EVENT_LIMITS,
|
|
618
|
+
PAGE,
|
|
619
|
+
MAX_PAGE_BYTES,
|
|
620
|
+
MAX_BYTES,
|
|
621
|
+
FIRST_RUN_HOURS,
|
|
622
|
+
TRUST,
|
|
623
|
+
REFUSAL_REASONS,
|
|
624
|
+
GAP_REASONS,
|
|
625
|
+
ERROR_CODES,
|
|
626
|
+
PROPOSED_CODES,
|
|
627
|
+
ERROR_ALIASES,
|
|
628
|
+
CONTRACT1_CODES,
|
|
629
|
+
canonicalCode,
|
|
630
|
+
SourceError,
|
|
631
|
+
parseSourceError,
|
|
632
|
+
SINCE_PATTERN,
|
|
633
|
+
SOURCE_PATTERN,
|
|
634
|
+
SCOPE_KEY_PATTERN,
|
|
635
|
+
sinceTime,
|
|
636
|
+
scopeProblems,
|
|
637
|
+
parseEventsListInput,
|
|
638
|
+
startTime,
|
|
639
|
+
cut,
|
|
640
|
+
eventHash,
|
|
641
|
+
makeEvent,
|
|
642
|
+
oldestFirst,
|
|
643
|
+
fitPage,
|
|
644
|
+
screenEvents,
|
|
645
|
+
PROBE,
|
|
646
|
+
PROBE_LIMITS,
|
|
647
|
+
parseProbeInput,
|
|
648
|
+
probeResult,
|
|
649
|
+
probeResultProblems,
|
|
650
|
+
eventsListResult,
|
|
651
|
+
eventProblems,
|
|
652
|
+
resultProblems
|
|
653
|
+
};
|