@parallax-rn/protocol 0.0.0-stage → 0.1.0-beta.3

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/dist/rules.js ADDED
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OLD_REJECTION = exports.NEW_REJECTION = exports.REJECTION_NAME = exports.SECRET_KEY = exports.REDACTED_TEXT = void 0;
4
+ exports.keyWords = keyWords;
5
+ exports.isSecretKey = isSecretKey;
6
+ exports.looksRandom = looksRandom;
7
+ exports.scrubText = scrubText;
8
+ exports.scrubLine = scrubLine;
9
+ exports.scrubField = scrubField;
10
+ exports.unhandledRejectionOf = unhandledRejectionOf;
11
+ /** What replaces a secret value in structured data and free text. */
12
+ exports.REDACTED_TEXT = '[redacted]';
13
+ /** Substring test on a key (`authToken`, `x-api-key`): cheap and wide. The core's `redactSecrets` uses it on object keys. */
14
+ exports.SECRET_KEY = /pass|secret|token|passcode|cvv|otp|pin$|credential|auth|cookie|session|api[-_]?key|private[-_]?key/i;
15
+ const SECRET_WORDS = new Set([
16
+ 'token', 'tokens', 'secret', 'secrets', 'password', 'passwords', 'passwd', 'passcode', 'passphrase', 'pass', 'auth', 'authorization', 'cookie', 'cookies', 'session', 'sessions',
17
+ 'credential', 'credentials', 'otp', 'pin', 'cvv', 'cvc', 'jwt', 'signature', 'bearer', 'apikey', 'privatekey', 'secretkey',
18
+ ]);
19
+ const KEY_QUALIFIERS = new Set(['api', 'private', 'secret', 'access', 'auth', 'encryption', 'signing', 'license', 'client', 'master']);
20
+ /** The words of a key (camelCase, snake_case and kebab-case parts), lower-cased. */
21
+ function keyWords(key) {
22
+ return key
23
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
24
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
25
+ .split(/[^A-Za-z0-9]+/)
26
+ .filter(Boolean)
27
+ .map(w => w.toLowerCase());
28
+ }
29
+ /**
30
+ * Word-based test (the picker's rule): `authorName`, `passenger` and `hotkey` are not secrets, `userAuthToken`, `api_key`, `sessionId` and `pin` are. A bare `key` is a
31
+ * secret only beside a word that says what kind of key it is.
32
+ */
33
+ function isSecretKey(key) {
34
+ const words = keyWords(key);
35
+ if (words.some(w => SECRET_WORDS.has(w)))
36
+ return true;
37
+ const at = words.indexOf('key');
38
+ return at > 0 && words.some((w, i) => i !== at && KEY_QUALIFIERS.has(w));
39
+ }
40
+ /** A value that looks like a credential: 20 or more characters of one word (no spaces) with letters and digits mixed, or a JWT, or a long hex or base64 run. */
41
+ function looksRandom(value) {
42
+ if (value.length < 20 || /\s/.test(value))
43
+ return false;
44
+ if (/^eyJ[\w-]+\.[\w-]+\.[\w-]*$/.test(value))
45
+ return true;
46
+ if (/^[0-9a-f]{24,}$/i.test(value))
47
+ return true;
48
+ if (!/^[A-Za-z0-9+/_=.-]+$/.test(value))
49
+ return false;
50
+ // a readable identifier or a path-like word is not a secret: needs digits and mixed case together
51
+ return /[A-Za-z]/.test(value) && /\d/.test(value) && /[A-Z]/.test(value) && /[a-z]/.test(value);
52
+ }
53
+ const TEXT_RULES = [
54
+ [/\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]{6,}/gi, `$1 ${exports.REDACTED_TEXT}`],
55
+ [/\b([A-Za-z0-9_-]*(?:token|key|secret|password|passwd|pwd)[A-Za-z0-9_-]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/gi, `$1$2${exports.REDACTED_TEXT}`],
56
+ [/[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g, exports.REDACTED_TEXT], // the last label has letters: `pkg@3.16.1` is a version
57
+ [/\b[0-9a-fA-F]{32,}\b/g, exports.REDACTED_TEXT],
58
+ ];
59
+ const LONG_RUN = /[A-Za-z0-9+/_-]{40,}={0,2}/g;
60
+ /** Every credential-shaped thing of the rules above, and EVERY run of 40 or more base64-alphabet characters. For text that is not a log line: a card, a header, a body. A cheap guard, not a promise. */
61
+ function scrubText(text) {
62
+ let out = text;
63
+ for (let i = 0; i < TEXT_RULES.length; i++) {
64
+ const rule = TEXT_RULES[i];
65
+ out = out.replace(rule[0], rule[1]);
66
+ }
67
+ return out.replace(LONG_RUN, exports.REDACTED_TEXT);
68
+ }
69
+ /**
70
+ * The scrub for a console line (plan 0013, Q9): the rules of `scrubText`, but a long run goes only when it looks like a secret. Log lines are full of file paths and filler, and
71
+ * `scrubText` turns a path under the home folder (`<home>/app/src/features/Home`) into `[redacted]` (and the root a Metro error names with it). A run with `+` or `=` is a secret (never in a path); a run
72
+ * without `/` is when it mixes digits and letters; in a run with `/` (a path or a URL) each part is judged alone and goes only when it is 32 or more characters of digits, upper
73
+ * and lower case.
74
+ */
75
+ function scrubLine(text) {
76
+ let out = text;
77
+ for (let i = 0; i < TEXT_RULES.length; i++) {
78
+ const rule = TEXT_RULES[i];
79
+ out = out.replace(rule[0], rule[1]);
80
+ }
81
+ return out.replace(LONG_RUN, secretRun);
82
+ }
83
+ /**
84
+ * The scrub for an approval card's one field (a file path or a command): `scrubText`, except that a run with `/` and no `+` or `=` (a path) is judged part by part, so
85
+ * `<home>/ParallaxFixtures/fx-e086/src/CompatScreen.tsx` stays readable. Stricter than `scrubLine`: a part goes at 20 characters of digits, upper and lower case, and a run
86
+ * without `/` goes whole, as in `scrubText`.
87
+ */
88
+ function scrubField(text) {
89
+ let out = text;
90
+ for (let i = 0; i < TEXT_RULES.length; i++) {
91
+ const rule = TEXT_RULES[i];
92
+ out = out.replace(rule[0], rule[1]);
93
+ }
94
+ out = out.replace(TOKEN_PREFIX, exports.REDACTED_TEXT).replace(URL_RUN, urlRun).replace(HEX_JOINED, hexJoined);
95
+ return out.replace(LONG_RUN, fieldRun).replace(MIXED_PART, exports.REDACTED_TEXT).replace(BARE_TOKEN, bareToken);
96
+ }
97
+ // The card's extra rules (a path stays readable, a credential does not): a known token prefix anywhere; a URL's secret-looking parts; hex joined by `_` or `-`; a part of 20 or more letters and
98
+ // digits that is not a file name; and a slash-joined run that is not a path (the shape of an AWS secret key).
99
+ const TOKEN_PREFIX = /(?<![A-Za-z0-9])(?:(?:gh[pousr])_[A-Za-z0-9]{16,}|github_pat_\w{16,}|xox[abpsr]-[A-Za-z0-9-]{8,}|sk_(?:live|test)_[A-Za-z0-9]{8,}|sk-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{12,}|AIza[\w-]{20,}|glpat-[\w-]{16,})/g;
100
+ const URL_RUN = /[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s'"`]+/g;
101
+ const HEX_JOINED = /(?<![0-9A-Za-z])[0-9a-fA-F]+(?:[_-][0-9a-fA-F]+)*(?![0-9A-Za-z])/g;
102
+ const MIXED_PART = /(?<![A-Za-z0-9])(?=[A-Za-z0-9]*\d)(?=[A-Za-z0-9]*[A-Za-z])[A-Za-z0-9]{20,}(?![A-Za-z0-9])(?!\.[A-Za-z][A-Za-z0-9]{0,4}(?![A-Za-z0-9]))/g;
103
+ const BARE_TOKEN = /[^\s'"`]+/g;
104
+ const hasExtension = (part) => /\.[A-Za-z0-9]{1,6}$/.test(part);
105
+ const urlRun = (url) => {
106
+ const at = url.indexOf('://') + 3;
107
+ const parts = url.slice(at).split('/'); // the first part is the host
108
+ let after = false; // everything after /services/ or /hooks/ is a secret
109
+ return url.slice(0, at) + parts.map((part, i) => {
110
+ const secret = i > 0 && (after || (part.length >= 20 && /\d/.test(part) && !hasExtension(part)));
111
+ if (i > 0 && (part === 'services' || part === 'hooks'))
112
+ after = true;
113
+ return secret ? exports.REDACTED_TEXT : part;
114
+ }).join('/');
115
+ };
116
+ const hexJoined = (run) => (run.replace(/[_-]/g, '').length >= 24 && /\d/.test(run) ? exports.REDACTED_TEXT : run);
117
+ const bareToken = (token) => {
118
+ if (token.startsWith('/') || token.startsWith('~/') || token.startsWith('./') || token.startsWith('../') || token.includes('://'))
119
+ return token;
120
+ const parts = token.split('/');
121
+ return parts.length >= 3 && token.length >= 20 && !parts.some(hasExtension) && /\d|[a-z][A-Z]/.test(token) ? exports.REDACTED_TEXT : token;
122
+ };
123
+ const fieldRun = (run) => {
124
+ if (/[+=]/.test(run) || !run.includes('/'))
125
+ return exports.REDACTED_TEXT;
126
+ return run.split('/').map(part => (part.length >= 20 && /\d/.test(part) && /[a-z]/.test(part) && /[A-Z]/.test(part) ? exports.REDACTED_TEXT : part)).join('/');
127
+ };
128
+ const secretRun = (run) => {
129
+ if (/[+=]/.test(run))
130
+ return exports.REDACTED_TEXT;
131
+ if (!run.includes('/'))
132
+ return /\d/.test(run) && /[A-Za-z]/.test(run) ? exports.REDACTED_TEXT : run;
133
+ return run.split('/').map(part => (part.length >= 32 && /\d/.test(part) && /[a-z]/.test(part) && /[A-Z]/.test(part) ? exports.REDACTED_TEXT : part)).join('/');
134
+ };
135
+ exports.REJECTION_NAME = 'UnhandledPromiseRejection';
136
+ // React Native 0.8x: onUnhandled -> ExceptionsManager.handleException -> console.error(Error); never reaches ErrorUtils' handler
137
+ exports.NEW_REJECTION = /^Uncaught \(in promise, id: \d+\)/;
138
+ // older React Native: console.warn(string)
139
+ exports.OLD_REJECTION = /^Possible unhandled promise rejection \(id: \d+\):\n?/;
140
+ /**
141
+ * An unhandled promise rejection as the app reports it to the console (plan 0006, step 3): React Native does NOT send it through the global error handler, so the console
142
+ * line is the only place it shows. `args` are the console call's arguments as the app has them (objects) or as a debugger describes them. Returns the error to record
143
+ * (named so that the Errors tab and `app_errors` can tell it), or null for any other console call.
144
+ */
145
+ function unhandledRejectionOf(level, args) {
146
+ const first = args[0];
147
+ if (level === 'error' && typeof first === 'object' && first !== null) {
148
+ const e = first;
149
+ if (typeof e.message === 'string' && exports.NEW_REJECTION.test(e.message)) {
150
+ // the Error React Native makes is created where the rejection was DETECTED (its stack is the tracker's); the rejected value, with the stack of where it was thrown, is its `cause`
151
+ const cause = typeof e.cause === 'object' && e.cause !== null ? e.cause : null;
152
+ const stack = typeof (cause === null || cause === void 0 ? void 0 : cause.stack) === 'string' && cause.stack !== '' ? cause.stack : typeof e.stack === 'string' ? e.stack : undefined;
153
+ return { name: exports.REJECTION_NAME, message: e.message, ...(stack !== undefined ? { stack } : {}) };
154
+ }
155
+ }
156
+ if (level === 'warn' && typeof first === 'string' && exports.OLD_REJECTION.test(first))
157
+ return { name: exports.REJECTION_NAME, message: first.replace(exports.OLD_REJECTION, '') || first };
158
+ return null;
159
+ }
@@ -0,0 +1,85 @@
1
+ export type Schema = {
2
+ readonly kind: 'string';
3
+ } | {
4
+ readonly kind: 'number';
5
+ readonly integer: boolean;
6
+ readonly min?: number;
7
+ } | {
8
+ readonly kind: 'boolean';
9
+ } | {
10
+ readonly kind: 'null';
11
+ } | {
12
+ readonly kind: 'unknown';
13
+ } | {
14
+ readonly kind: 'literal';
15
+ readonly value: string | number | boolean;
16
+ } | {
17
+ readonly kind: 'enum';
18
+ readonly values: readonly string[];
19
+ } | {
20
+ readonly kind: 'relativePath';
21
+ } | {
22
+ readonly kind: 'array';
23
+ readonly item: Schema;
24
+ } | {
25
+ readonly kind: 'tuple';
26
+ readonly items: readonly Schema[];
27
+ } | {
28
+ readonly kind: 'record';
29
+ readonly value: Schema;
30
+ } | {
31
+ readonly kind: 'object';
32
+ readonly props: {
33
+ readonly [key: string]: Schema;
34
+ };
35
+ readonly optional: readonly string[];
36
+ } | {
37
+ readonly kind: 'union';
38
+ readonly options: readonly Schema[];
39
+ };
40
+ export interface Typed<T> {
41
+ readonly schema: Schema;
42
+ readonly is: (value: unknown) => value is T;
43
+ }
44
+ export type Infer<S> = S extends {
45
+ is(value: unknown): value is infer T;
46
+ } ? T : never;
47
+ type Simplify<T> = {
48
+ [K in keyof T]: T[K];
49
+ } & {};
50
+ export type Result<T> = {
51
+ readonly ok: true;
52
+ readonly value: T;
53
+ } | {
54
+ readonly ok: false;
55
+ readonly error: string;
56
+ };
57
+ /** A path inside a package: relative, forward slashes, no drive letter, no `..`, no empty segments. */
58
+ export declare function isRelativePath(value: string): boolean;
59
+ /** Returns an error message (with a path) for the first violation, or null when the value matches. */
60
+ export declare function check(schema: Schema, value: unknown, path?: string): string | null;
61
+ export declare function parse<T>(type: Typed<T>, value: unknown): Result<T>;
62
+ export declare const t: {
63
+ string: () => Typed<string>;
64
+ number: () => Typed<number>;
65
+ int: (min?: number) => Typed<number>;
66
+ boolean: () => Typed<boolean>;
67
+ null: () => Typed<null>;
68
+ unknown: () => Typed<unknown>;
69
+ literal: <V extends string | number | boolean>(value: V) => Typed<V>;
70
+ enumOf: <V extends string>(values: readonly V[]) => Typed<V>;
71
+ relativePath: () => Typed<string>;
72
+ array: <T>(item: Typed<T>) => Typed<T[]>;
73
+ tuple: <A extends readonly Typed<any>[]>(items: readonly [...A]) => Typed<{ [K in keyof A]: Infer<A[K]>; }>;
74
+ record: <T>(value: Typed<T>) => Typed<{
75
+ [key: string]: T;
76
+ }>;
77
+ object: <P extends {
78
+ [key: string]: Typed<any>;
79
+ }, O extends keyof P & string = never>(props: P, optional?: readonly O[]) => Typed<Simplify<{ [K in Exclude<keyof P, O>]: Infer<P[K]>; } & { [K in O]?: Infer<P[K]>; }>>;
80
+ union: <A extends readonly Typed<any>[]>(options: readonly [...A]) => Typed<Infer<A[number]>>;
81
+ };
82
+ /** JSON with sorted object keys: the same value always serializes to the same text. */
83
+ export declare function canonicalJson(value: unknown): string;
84
+ export {};
85
+ //# sourceMappingURL=schema.d.ts.map
package/dist/schema.js ADDED
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ // A tiny schema language. One definition gives the TypeScript type, the runtime validator and the canonical
3
+ // description used by the contract snapshot test. Dependency-free on purpose (decision 0007).
4
+ //
5
+ // Validators are tolerant readers: unknown extra properties on objects and extra trailing items in tuples are accepted,
6
+ // so a newer peer that adds optional fields (a minor protocol change) does not break an older reader.
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.t = void 0;
9
+ exports.isRelativePath = isRelativePath;
10
+ exports.check = check;
11
+ exports.parse = parse;
12
+ exports.canonicalJson = canonicalJson;
13
+ function isPlainObject(value) {
14
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
15
+ }
16
+ /** A path inside a package: relative, forward slashes, no drive letter, no `..`, no empty segments. */
17
+ function isRelativePath(value) {
18
+ if (value.length === 0 || value.charAt(0) === '/' || value.indexOf('\\') !== -1 || value.indexOf('\u0000') !== -1)
19
+ return false;
20
+ if (/^[A-Za-z]:/.test(value))
21
+ return false;
22
+ const segments = value.split('/');
23
+ for (let i = 0; i < segments.length; i++) {
24
+ const segment = segments[i];
25
+ if (segment === '' || segment === '..' || segment === '.')
26
+ return false;
27
+ }
28
+ return true;
29
+ }
30
+ /** Returns an error message (with a path) for the first violation, or null when the value matches. */
31
+ function check(schema, value, path = '$') {
32
+ switch (schema.kind) {
33
+ case 'string':
34
+ return typeof value === 'string' ? null : `${path}: expected a string`;
35
+ case 'number': {
36
+ if (typeof value !== 'number' || !isFinite(value))
37
+ return `${path}: expected ${schema.integer ? 'an integer' : 'a finite number'}`;
38
+ if (schema.integer && Math.floor(value) !== value)
39
+ return `${path}: expected an integer`;
40
+ if (schema.min !== undefined && value < schema.min)
41
+ return `${path}: expected a number >= ${schema.min}`;
42
+ return null;
43
+ }
44
+ case 'boolean':
45
+ return typeof value === 'boolean' ? null : `${path}: expected a boolean`;
46
+ case 'null':
47
+ return value === null ? null : `${path}: expected null`;
48
+ case 'unknown':
49
+ return null;
50
+ case 'literal':
51
+ return value === schema.value ? null : `${path}: expected ${JSON.stringify(schema.value)}`;
52
+ case 'enum':
53
+ return typeof value === 'string' && schema.values.indexOf(value) !== -1 ? null : `${path}: expected one of ${schema.values.join(', ')}`;
54
+ case 'relativePath':
55
+ return typeof value === 'string' && isRelativePath(value) ? null : `${path}: expected a project-relative path with forward slashes`;
56
+ case 'array': {
57
+ if (!Array.isArray(value))
58
+ return `${path}: expected an array`;
59
+ for (let i = 0; i < value.length; i++) {
60
+ const error = check(schema.item, value[i], `${path}[${i}]`);
61
+ if (error)
62
+ return error;
63
+ }
64
+ return null;
65
+ }
66
+ case 'tuple': {
67
+ if (!Array.isArray(value))
68
+ return `${path}: expected an array`;
69
+ if (value.length < schema.items.length)
70
+ return `${path}: expected at least ${schema.items.length} items`;
71
+ for (let i = 0; i < schema.items.length; i++) {
72
+ const item = schema.items[i];
73
+ if (item === undefined)
74
+ continue;
75
+ const error = check(item, value[i], `${path}[${i}]`);
76
+ if (error)
77
+ return error;
78
+ }
79
+ return null;
80
+ }
81
+ case 'record': {
82
+ if (!isPlainObject(value))
83
+ return `${path}: expected an object`;
84
+ for (const key of Object.keys(value)) {
85
+ const error = check(schema.value, value[key], `${path}.${key}`);
86
+ if (error)
87
+ return error;
88
+ }
89
+ return null;
90
+ }
91
+ case 'object': {
92
+ if (!isPlainObject(value))
93
+ return `${path}: expected an object`;
94
+ for (const key of Object.keys(schema.props)) {
95
+ const prop = schema.props[key];
96
+ if (prop === undefined)
97
+ continue;
98
+ const present = Object.prototype.hasOwnProperty.call(value, key) && value[key] !== undefined;
99
+ if (!present) {
100
+ if (schema.optional.indexOf(key) !== -1)
101
+ continue;
102
+ return `${path}.${key}: missing`;
103
+ }
104
+ const error = check(prop, value[key], `${path}.${key}`);
105
+ if (error)
106
+ return error;
107
+ }
108
+ return null;
109
+ }
110
+ case 'union': {
111
+ const errors = [];
112
+ for (const option of schema.options) {
113
+ const error = check(option, value, path);
114
+ if (error === null)
115
+ return null;
116
+ errors.push(error);
117
+ }
118
+ return `${path}: matches none of the options (${errors.join('; ')})`;
119
+ }
120
+ }
121
+ }
122
+ function typed(schema) {
123
+ return { schema, is: (value) => check(schema, value) === null };
124
+ }
125
+ function parse(type, value) {
126
+ const error = check(type.schema, value);
127
+ return error === null ? { ok: true, value: value } : { ok: false, error };
128
+ }
129
+ exports.t = {
130
+ string: () => typed({ kind: 'string' }),
131
+ number: () => typed({ kind: 'number', integer: false }),
132
+ int: (min) => typed(min === undefined ? { kind: 'number', integer: true } : { kind: 'number', integer: true, min }),
133
+ boolean: () => typed({ kind: 'boolean' }),
134
+ null: () => typed({ kind: 'null' }),
135
+ unknown: () => typed({ kind: 'unknown' }),
136
+ literal: (value) => typed({ kind: 'literal', value }),
137
+ enumOf: (values) => typed({ kind: 'enum', values }),
138
+ relativePath: () => typed({ kind: 'relativePath' }),
139
+ array: (item) => typed({ kind: 'array', item: item.schema }),
140
+ tuple: (items) => typed({ kind: 'tuple', items: items.map(item => item.schema) }),
141
+ record: (value) => typed({ kind: 'record', value: value.schema }),
142
+ object: (props, optional) => {
143
+ const schemas = {};
144
+ for (const key of Object.keys(props)) {
145
+ const prop = props[key];
146
+ if (prop)
147
+ schemas[key] = prop.schema;
148
+ }
149
+ return typed({ kind: 'object', props: schemas, optional: optional ? optional.slice() : [] });
150
+ },
151
+ union: (options) => typed({ kind: 'union', options: options.map(option => option.schema) }),
152
+ };
153
+ /** JSON with sorted object keys: the same value always serializes to the same text. */
154
+ function canonicalJson(value) {
155
+ return JSON.stringify(sortKeys(value), null, 2);
156
+ }
157
+ function sortKeys(value) {
158
+ if (Array.isArray(value))
159
+ return value.map(sortKeys);
160
+ if (isPlainObject(value)) {
161
+ const sorted = {};
162
+ for (const key of Object.keys(value).sort())
163
+ sorted[key] = sortKeys(value[key]);
164
+ return sorted;
165
+ }
166
+ return value;
167
+ }
@@ -0,0 +1,7 @@
1
+ export declare const INJECTED_ID_PREFIX = "prn:";
2
+ export declare function injectedTestId(file: string, n: number): string;
3
+ export declare function parseInjectedTestId(id: string): {
4
+ readonly file: string;
5
+ readonly n: number;
6
+ } | null;
7
+ //# sourceMappingURL=source-id.d.ts.map
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.INJECTED_ID_PREFIX = void 0;
4
+ exports.injectedTestId = injectedTestId;
5
+ exports.parseInjectedTestId = parseInjectedTestId;
6
+ // Identifier of an element whose testID the build plugin injected (opt-in, decision 0008):
7
+ // `prn:<project-relative file>::<element number in that file>`.
8
+ const schema_js_1 = require("./schema.js");
9
+ exports.INJECTED_ID_PREFIX = 'prn:';
10
+ function injectedTestId(file, n) {
11
+ return `${exports.INJECTED_ID_PREFIX}${file}::${n}`;
12
+ }
13
+ function parseInjectedTestId(id) {
14
+ if (id.indexOf(exports.INJECTED_ID_PREFIX) !== 0)
15
+ return null;
16
+ const rest = id.slice(exports.INJECTED_ID_PREFIX.length);
17
+ const cut = rest.lastIndexOf('::');
18
+ if (cut < 1)
19
+ return null;
20
+ const file = rest.slice(0, cut);
21
+ const digits = rest.slice(cut + 2);
22
+ if (!/^(0|[1-9][0-9]*)$/.test(digits) || !(0, schema_js_1.isRelativePath)(file))
23
+ return null;
24
+ return { file, n: Number(digits) };
25
+ }
@@ -0,0 +1,9 @@
1
+ /** The two streams that exist since protocol 0.1 and have their own fields; they are never sent in `sources`. */
2
+ export declare const BUILT_IN_SOURCES: readonly ['logs', 'errors'];
3
+ /** `kind` (lower-case letters, digits, `_` and `-`, starting with a letter, at most 32) with an optional `:instance` (letters, digits, `.`, `_`, `-`, at most 64). */
4
+ export declare const SOURCE_NAME_PATTERN = "^[a-z][a-z0-9_-]{0,31}(:[A-Za-z0-9._-]{1,64})?$";
5
+ /** Whether a name is a valid name for a data source in `sources` (the built-in streams are not). */
6
+ export declare function isSourceName(value: unknown): value is string;
7
+ /** The kind of a source name: `state:redux` is of kind `state`. */
8
+ export declare function sourceKind(name: string): string;
9
+ //# sourceMappingURL=sources.d.ts.map
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ // Namespaced data sources (protocol 0.5; plan 0003, "Extension points for stage 4"): the SDK can carry more than logs and errors, each kind of data under its
3
+ // own name, with its own sequence numbers and its own ring buffer on both sides. The built-in streams `logs` and `errors` keep their first-class fields; every
4
+ // other source is named `kind` or `kind:instance` (`network`, `state:redux`, `query:main`). A name is lower-case so it can be a tool argument and a file name.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SOURCE_NAME_PATTERN = exports.BUILT_IN_SOURCES = void 0;
7
+ exports.isSourceName = isSourceName;
8
+ exports.sourceKind = sourceKind;
9
+ /** The two streams that exist since protocol 0.1 and have their own fields; they are never sent in `sources`. */
10
+ exports.BUILT_IN_SOURCES = ['logs', 'errors'];
11
+ /** `kind` (lower-case letters, digits, `_` and `-`, starting with a letter, at most 32) with an optional `:instance` (letters, digits, `.`, `_`, `-`, at most 64). */
12
+ exports.SOURCE_NAME_PATTERN = '^[a-z][a-z0-9_-]{0,31}(:[A-Za-z0-9._-]{1,64})?$';
13
+ const SOURCE_NAME = new RegExp(exports.SOURCE_NAME_PATTERN);
14
+ /** Whether a name is a valid name for a data source in `sources` (the built-in streams are not). */
15
+ function isSourceName(value) {
16
+ return typeof value === 'string' && SOURCE_NAME.test(value) && !exports.BUILT_IN_SOURCES.includes(value);
17
+ }
18
+ /** The kind of a source name: `state:redux` is of kind `state`. */
19
+ function sourceKind(name) {
20
+ const colon = name.indexOf(':');
21
+ return colon === -1 ? name : name.slice(0, colon);
22
+ }
@@ -0,0 +1,17 @@
1
+ export type ProtocolVersion = readonly [major: number, minor: number];
2
+ /** One version for the whole contract; independent of the package versions. Starts at 0.1; 0.2 added the optional `plugin` field of a source table, 0.3 the optional `root` field, 0.4 the error codes `denied_by_user`, `core_unavailable` and `core_version_mismatch` (decision 0016), 0.5 the optional `sources` of the handshake, the drain request and result and the push batch (namespaced data sources), 0.6 the typed `data` of the `network`, `navigation`, `state:*` and `query:*` sources (`networkEntryT`, `navigationEntryT`, `stateEntryT`; plan 0013 Q7: a core drops and counts an entry that does not match). */
3
+ export declare const PROTOCOL_VERSION: ProtocolVersion;
4
+ export type ProtocolRelation = 'same' | 'remote-newer-minor' | 'remote-older-minor' | 'incompatible';
5
+ export interface ProtocolCheck {
6
+ /** False means "mismatch": the caller shows a warning (it is never a reason to stop). */
7
+ readonly compatible: boolean;
8
+ readonly relation: ProtocolRelation;
9
+ readonly message: string;
10
+ }
11
+ export declare function formatProtocol(version: ProtocolVersion): string;
12
+ /**
13
+ * Mismatch: the majors differ, or the major is 0 and the minors differ (while the major is 0 compatibility holds only
14
+ * within one `0.minor`). From major 1 on, a different minor is compatible and only noted.
15
+ */
16
+ export declare function compareProtocol(local: ProtocolVersion, remote: ProtocolVersion): ProtocolCheck;
17
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ // Protocol version rules (decision 0012).
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.PROTOCOL_VERSION = void 0;
5
+ exports.formatProtocol = formatProtocol;
6
+ exports.compareProtocol = compareProtocol;
7
+ /** One version for the whole contract; independent of the package versions. Starts at 0.1; 0.2 added the optional `plugin` field of a source table, 0.3 the optional `root` field, 0.4 the error codes `denied_by_user`, `core_unavailable` and `core_version_mismatch` (decision 0016), 0.5 the optional `sources` of the handshake, the drain request and result and the push batch (namespaced data sources), 0.6 the typed `data` of the `network`, `navigation`, `state:*` and `query:*` sources (`networkEntryT`, `navigationEntryT`, `stateEntryT`; plan 0013 Q7: a core drops and counts an entry that does not match). */
8
+ exports.PROTOCOL_VERSION = [0, 6];
9
+ function formatProtocol(version) {
10
+ return `${version[0]}.${version[1]}`;
11
+ }
12
+ /**
13
+ * Mismatch: the majors differ, or the major is 0 and the minors differ (while the major is 0 compatibility holds only
14
+ * within one `0.minor`). From major 1 on, a different minor is compatible and only noted.
15
+ */
16
+ function compareProtocol(local, remote) {
17
+ const pair = `local ${formatProtocol(local)}, remote ${formatProtocol(remote)}`;
18
+ if (local[0] !== remote[0]) {
19
+ return { compatible: false, relation: 'incompatible', message: `Protocol major versions differ (${pair}).` };
20
+ }
21
+ if (local[1] === remote[1]) {
22
+ return { compatible: true, relation: 'same', message: `Protocol ${formatProtocol(local)}.` };
23
+ }
24
+ if (local[0] === 0) {
25
+ return { compatible: false, relation: 'incompatible', message: `Protocol minor versions differ while the major version is 0 (${pair}).` };
26
+ }
27
+ return remote[1] > local[1]
28
+ ? { compatible: true, relation: 'remote-newer-minor', message: `The remote side speaks a newer minor protocol version (${pair}); unknown fields are ignored.` }
29
+ : { compatible: true, relation: 'remote-older-minor', message: `The remote side speaks an older minor protocol version (${pair}); optional fields may be missing.` };
30
+ }
package/package.json CHANGED
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "name": "@parallax-rn/protocol",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.3",
4
+ "description": "Shared contract for Parallax for React Native: wire shapes, validators, error codes, global names and protocol version rules. Tested on React Native 0.87.1 (no dependencies).",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist",
10
+ "!dist/**/*.test.*",
11
+ "!dist/*.tsbuildinfo",
12
+ "contract.snapshot.json",
13
+ "!dist/**/*.map"
14
+ ],
15
+ "engines": {
16
+ "node": "^20.19.4 || ^22.13.0 || ^24.3.0 || >=25.0.0"
17
+ },
18
+ "sideEffects": false,
19
+ "scripts": {
20
+ "contract:update": "node scripts/update-contract-snapshot.mjs"
21
+ }
22
+ }