precognition-plus 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/LICENSE +21 -0
- package/README.md +31 -2
- package/dist/index.d.ts +19 -0
- package/dist/index.js +270 -0
- package/package.json +59 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CodeNyra
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
1
|
-
#
|
|
1
|
+
# precognition-plus
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The browser side of [Precognition Plus](https://github.com/codenyra/precognition-plus).
|
|
4
|
+
It checks the simple rules of your Laravel FormRequests (`required`, `integer`,
|
|
5
|
+
`min`, `max`, `regex` and a few more) in the browser, so a Precognition form
|
|
6
|
+
only asks the server about fields with rules like `unique`, `exists`, Rule
|
|
7
|
+
objects or closures.
|
|
8
|
+
|
|
9
|
+
It works together with the Laravel package, `codenyra/precognition-plus` on
|
|
10
|
+
Composer. Without it, forms work like plain Precognition.
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
composer require codenyra/precognition-plus
|
|
14
|
+
npm install precognition-plus
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
// resources/js/app.ts
|
|
19
|
+
import { setupPrecognitionPlus } from 'precognition-plus'
|
|
20
|
+
|
|
21
|
+
setupPrecognitionPlus()
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
Your forms stay as they are. The tests cover Inertia 3's `useForm` and
|
|
25
|
+
`<Form>` in Vue and `useForm` in React. Svelte, `useHttp()` and plain
|
|
26
|
+
`laravel-precognition` go through the same Precognition client, so they
|
|
27
|
+
should work too.
|
|
28
|
+
|
|
29
|
+
Anyone who can submit a form can read its browser rules, including `in`
|
|
30
|
+
lists and `regex` patterns. The
|
|
31
|
+
[documentation](https://github.com/codenyra/precognition-plus/tree/main/docs)
|
|
32
|
+
says which rules run where, and how to keep one on the server.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
declare function setupPrecognitionPlus(): () => void;
|
|
2
|
+
|
|
3
|
+
interface ClientRule {
|
|
4
|
+
rule: string;
|
|
5
|
+
params: string[];
|
|
6
|
+
message: string;
|
|
7
|
+
}
|
|
8
|
+
type SizeType = 'string' | 'numeric' | 'array' | 'file';
|
|
9
|
+
interface FieldSchema {
|
|
10
|
+
rules: ClientRule[];
|
|
11
|
+
server: boolean;
|
|
12
|
+
nullable: boolean;
|
|
13
|
+
type: SizeType;
|
|
14
|
+
depends?: string[];
|
|
15
|
+
values?: Record<string, string>;
|
|
16
|
+
}
|
|
17
|
+
type ValidationSchema = Record<string, FieldSchema>;
|
|
18
|
+
|
|
19
|
+
export { type ClientRule, type FieldSchema, type ValidationSchema, setupPrecognitionPlus };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import { client, HttpResponseError } from 'laravel-precognition';
|
|
2
|
+
|
|
3
|
+
// src/core/interceptor.ts
|
|
4
|
+
|
|
5
|
+
// src/core/utils.ts
|
|
6
|
+
var isObject = (value) => value !== null && typeof value === "object";
|
|
7
|
+
var isFile = (value) => typeof Blob !== "undefined" && value instanceof Blob;
|
|
8
|
+
var isPlainObject = (value) => isObject(value) && !Array.isArray(value) && !isFile(value);
|
|
9
|
+
function getPath(data, path) {
|
|
10
|
+
let current = data;
|
|
11
|
+
for (const segment of path.split(".")) {
|
|
12
|
+
if (!isObject(current) || !(segment in current)) {
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
current = current[segment];
|
|
16
|
+
}
|
|
17
|
+
return current;
|
|
18
|
+
}
|
|
19
|
+
function toPhpString(value) {
|
|
20
|
+
if (value === true) return "1";
|
|
21
|
+
if (value === false || value === null || value === void 0) return "";
|
|
22
|
+
return String(value);
|
|
23
|
+
}
|
|
24
|
+
function isNumeric(value) {
|
|
25
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
26
|
+
return typeof value === "string" && /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/.test(value);
|
|
27
|
+
}
|
|
28
|
+
function phpStringEquals(a, b) {
|
|
29
|
+
return isNumeric(a) && isNumeric(b) ? Number(a) === Number(b) : a === b;
|
|
30
|
+
}
|
|
31
|
+
var UNTRIMMED = /* @__PURE__ */ new Set(["current_password", "password", "password_confirmation"]);
|
|
32
|
+
function normalize(value, attribute) {
|
|
33
|
+
if (typeof value !== "string") return value;
|
|
34
|
+
const trimmed = UNTRIMMED.has(attribute) ? value : value.trim();
|
|
35
|
+
return trimmed === "" ? null : trimmed;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// src/core/engine.ts
|
|
39
|
+
var IMPLICIT = /* @__PURE__ */ new Set(["required"]);
|
|
40
|
+
function checkField(schema, validators2, attribute, data) {
|
|
41
|
+
const field = schema[attribute];
|
|
42
|
+
if (!field) {
|
|
43
|
+
return { message: null, server: true };
|
|
44
|
+
}
|
|
45
|
+
const value = normalize(getPath(data, attribute), attribute);
|
|
46
|
+
const optional = value === void 0 || value === null && field.nullable;
|
|
47
|
+
let server = field.server;
|
|
48
|
+
const context = {
|
|
49
|
+
attribute,
|
|
50
|
+
field,
|
|
51
|
+
other: (path) => normalize(getPath(data, path), path)
|
|
52
|
+
};
|
|
53
|
+
for (const rule of field.rules) {
|
|
54
|
+
if (optional && !IMPLICIT.has(rule.rule)) continue;
|
|
55
|
+
const validator = validators2[rule.rule];
|
|
56
|
+
if (!validator) {
|
|
57
|
+
server = true;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
let passes;
|
|
61
|
+
try {
|
|
62
|
+
passes = validator(value, rule, context);
|
|
63
|
+
} catch {
|
|
64
|
+
server = true;
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
if (!passes) {
|
|
68
|
+
return { message: withInput(rule.message, value, field), server };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return { message: null, server };
|
|
72
|
+
}
|
|
73
|
+
function withInput(message, value, field) {
|
|
74
|
+
if (!message.includes(":input")) return message;
|
|
75
|
+
if (value !== null && value !== void 0 && !["string", "number", "boolean"].includes(typeof value)) return message;
|
|
76
|
+
const shown = field.values?.[toPhpString(value)] ?? (typeof value === "boolean" ? String(value) : value === null || value === void 0 ? "empty" : String(value));
|
|
77
|
+
return message.split(":input").join(shown);
|
|
78
|
+
}
|
|
79
|
+
function schemaKey(method, url) {
|
|
80
|
+
const base = typeof window === "undefined" ? "http://localhost" : window.location.origin;
|
|
81
|
+
return `${method.toLowerCase()} /` + new URL(url, base).pathname.replace(/^\/+|\/+$/g, "");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/core/validators.ts
|
|
85
|
+
var isStringy = (value) => typeof value === "string" || typeof value === "number" && Number.isFinite(value);
|
|
86
|
+
function measure(value, context) {
|
|
87
|
+
if (context.field.type === "numeric" && isNumeric(value)) return Number(value);
|
|
88
|
+
if (Array.isArray(value)) return value.length;
|
|
89
|
+
if (isFile(value)) return value.size / 1024;
|
|
90
|
+
if (isPlainObject(value)) return Object.keys(value).length;
|
|
91
|
+
return [...toPhpString(value)].length;
|
|
92
|
+
}
|
|
93
|
+
var param = (rule, index = 0) => Number(rule.params[index]);
|
|
94
|
+
var required = (value) => !(value === null || value === void 0 || typeof value === "string" && value.trim() === "" || Array.isArray(value) && value.length === 0 || isPlainObject(value) && Object.keys(value).length === 0);
|
|
95
|
+
var integer = (value) => value === true || typeof value === "number" && Number.isInteger(value) || typeof value === "string" && /^\s*[+-]?(0|[1-9]\d*)\s*$/.test(value);
|
|
96
|
+
var validators = {
|
|
97
|
+
required,
|
|
98
|
+
string: (value) => typeof value === "string",
|
|
99
|
+
numeric: (value) => isNumeric(value),
|
|
100
|
+
integer,
|
|
101
|
+
boolean: (value) => [true, false, 0, 1, "0", "1"].includes(value),
|
|
102
|
+
min: (value, rule, context) => measure(value, context) >= param(rule),
|
|
103
|
+
max: (value, rule, context) => measure(value, context) <= param(rule),
|
|
104
|
+
between: (value, rule, context) => {
|
|
105
|
+
const actual = measure(value, context);
|
|
106
|
+
return actual >= param(rule, 0) && actual <= param(rule, 1);
|
|
107
|
+
},
|
|
108
|
+
email: (value) => typeof value === "string" && /^[^\s@]+@[^\s@]+$/.test(value),
|
|
109
|
+
regex: (value, rule) => isStringy(value) && new RegExp(rule.params[0], rule.params[1]).test(String(value)),
|
|
110
|
+
in: (value, rule) => !Array.isArray(value) && rule.params.some((allowed) => phpStringEquals(toPhpString(value), allowed)),
|
|
111
|
+
confirmed: (value, rule, context) => value === context.other(rule.params[0])
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
// src/core/interceptor.ts
|
|
115
|
+
var METHODS = ["get", "post", "put", "patch", "delete", "query"];
|
|
116
|
+
var HEADER = "Precognition-Rules";
|
|
117
|
+
function setupPrecognitionPlus() {
|
|
118
|
+
let schemas = /* @__PURE__ */ new Map();
|
|
119
|
+
let cache = /* @__PURE__ */ new Map();
|
|
120
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
121
|
+
let page;
|
|
122
|
+
const onNavigate = (event) => {
|
|
123
|
+
const url = event.detail?.page?.url;
|
|
124
|
+
if (url === page) return;
|
|
125
|
+
page = url;
|
|
126
|
+
schemas = /* @__PURE__ */ new Map();
|
|
127
|
+
cache = /* @__PURE__ */ new Map();
|
|
128
|
+
};
|
|
129
|
+
globalThis.document?.addEventListener("inertia:navigate", onNavigate);
|
|
130
|
+
const fileIds = /* @__PURE__ */ new WeakMap();
|
|
131
|
+
let files = 0;
|
|
132
|
+
const withFileIds = (_key, value) => {
|
|
133
|
+
if (!isFile(value)) return value;
|
|
134
|
+
if (!fileIds.has(value)) fileIds.set(value, ++files);
|
|
135
|
+
return { file: fileIds.get(value) };
|
|
136
|
+
};
|
|
137
|
+
const valueOf = (data, entry, schema) => JSON.stringify([entry, ...schema?.[entry]?.depends ?? []].map((path) => getPath(data, path)), withFileIds);
|
|
138
|
+
const remember = (key, values, server) => {
|
|
139
|
+
for (const [entry, value] of values) {
|
|
140
|
+
cache.set(`${key} ${entry}`, { value, errors: server[entry] ? { [entry]: server[entry] } : {} });
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
const originals = Object.fromEntries(METHODS.map((method) => [method, client[method]]));
|
|
144
|
+
for (const method of METHODS) {
|
|
145
|
+
client[method] = (url, data = {}, config = {}) => {
|
|
146
|
+
const key = schemaKey(method, url);
|
|
147
|
+
const only = config.only ?? config.validate;
|
|
148
|
+
if (!only || config.precognitive === false) {
|
|
149
|
+
return originals[method](url, data, config);
|
|
150
|
+
}
|
|
151
|
+
const schema = schemas.get(key);
|
|
152
|
+
if (schema === void 0) {
|
|
153
|
+
const rulesIn = (response) => {
|
|
154
|
+
const rules = typeof response.data === "object" ? response.data?.rules : void 0;
|
|
155
|
+
return rules && typeof rules === "object" ? rules : null;
|
|
156
|
+
};
|
|
157
|
+
const sent = JSON.parse(JSON.stringify(data, withFileIds));
|
|
158
|
+
const learn = (response, server = {}) => {
|
|
159
|
+
const learned = rulesIn(response);
|
|
160
|
+
const entries = Array.from(only).filter((entry) => !entry.includes("*"));
|
|
161
|
+
schemas.set(key, learned);
|
|
162
|
+
remember(key, new Map(entries.map((entry) => [entry, valueOf(sent, entry, learned)])), server);
|
|
163
|
+
};
|
|
164
|
+
return originals[method](url, data, {
|
|
165
|
+
...config,
|
|
166
|
+
headers: { ...config.headers, [HEADER]: "true" },
|
|
167
|
+
onPrecognitionSuccess: (response) => {
|
|
168
|
+
learn(response);
|
|
169
|
+
return config.onPrecognitionSuccess?.(response) ?? response;
|
|
170
|
+
},
|
|
171
|
+
onSuccess: (response) => {
|
|
172
|
+
if (response.status !== 200 || !rulesIn(response)) {
|
|
173
|
+
return config.onSuccess?.(response) ?? response;
|
|
174
|
+
}
|
|
175
|
+
learn(response);
|
|
176
|
+
return succeed(config, { ...response, status: 204, data: "" });
|
|
177
|
+
},
|
|
178
|
+
onValidationError: (response, error) => {
|
|
179
|
+
learn(response, response.data?.errors ?? {});
|
|
180
|
+
return config.onValidationError ? config.onValidationError(response, error) : Promise.reject(error);
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
if (schema === null) {
|
|
185
|
+
return originals[method](url, data, config);
|
|
186
|
+
}
|
|
187
|
+
const local = {};
|
|
188
|
+
const kept = {};
|
|
189
|
+
const send = [];
|
|
190
|
+
const values = /* @__PURE__ */ new Map();
|
|
191
|
+
for (const entry of Array.from(only)) {
|
|
192
|
+
if (entry.includes("*")) {
|
|
193
|
+
send.push(entry);
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
const { message, server } = checkField(schema, validators, entry, data);
|
|
197
|
+
if (message) {
|
|
198
|
+
local[entry] = [message];
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
if (!server) continue;
|
|
202
|
+
const value = valueOf(data, entry, schema);
|
|
203
|
+
const cached = cache.get(`${key} ${entry}`);
|
|
204
|
+
if (cached?.value === value) {
|
|
205
|
+
Object.assign(kept, cached.errors);
|
|
206
|
+
} else {
|
|
207
|
+
send.push(entry);
|
|
208
|
+
values.set(entry, value);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
inflight.get(key)?.abort();
|
|
212
|
+
inflight.delete(key);
|
|
213
|
+
const errors = (server = {}) => ({ ...kept, ...server, ...local });
|
|
214
|
+
if (send.length === 0) {
|
|
215
|
+
return answer(config, errors());
|
|
216
|
+
}
|
|
217
|
+
const controller = new AbortController();
|
|
218
|
+
config.signal?.addEventListener("abort", () => controller.abort());
|
|
219
|
+
inflight.set(key, controller);
|
|
220
|
+
return originals[method](url, data, {
|
|
221
|
+
...config,
|
|
222
|
+
only: send,
|
|
223
|
+
signal: controller.signal,
|
|
224
|
+
onPrecognitionSuccess: (response) => {
|
|
225
|
+
remember(key, values, {});
|
|
226
|
+
const all = errors();
|
|
227
|
+
return Object.keys(all).length ? fail(config, all) : config.onPrecognitionSuccess?.(response) ?? response;
|
|
228
|
+
},
|
|
229
|
+
onValidationError: (response) => {
|
|
230
|
+
const server = response.data?.errors ?? {};
|
|
231
|
+
remember(key, values, server);
|
|
232
|
+
return fail(config, errors(server), response);
|
|
233
|
+
},
|
|
234
|
+
onFinish: () => {
|
|
235
|
+
if (inflight.get(key) === controller) inflight.delete(key);
|
|
236
|
+
config.onFinish?.();
|
|
237
|
+
}
|
|
238
|
+
});
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
return () => {
|
|
242
|
+
for (const method of METHODS) client[method] = originals[method];
|
|
243
|
+
globalThis.document?.removeEventListener("inertia:navigate", onNavigate);
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
function fail(config, errors, base) {
|
|
247
|
+
const response = {
|
|
248
|
+
status: 422,
|
|
249
|
+
headers: { ...base?.headers, precognition: "true" },
|
|
250
|
+
data: { ...typeof base?.data === "object" ? base.data : {}, errors }
|
|
251
|
+
};
|
|
252
|
+
const error = new HttpResponseError(response);
|
|
253
|
+
return config.onValidationError ? config.onValidationError(response, error) : Promise.reject(error);
|
|
254
|
+
}
|
|
255
|
+
async function answer(config, errors) {
|
|
256
|
+
if (config.onBefore?.() === false) return null;
|
|
257
|
+
config.onStart?.();
|
|
258
|
+
try {
|
|
259
|
+
if (Object.keys(errors).length) return await fail(config, errors);
|
|
260
|
+
return await succeed(config, { status: 204, data: "", headers: { precognition: "true", "precognition-success": "true" } });
|
|
261
|
+
} finally {
|
|
262
|
+
config.onFinish?.();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
async function succeed(config, response) {
|
|
266
|
+
const payload = await config.onPrecognitionSuccess?.(response) ?? response;
|
|
267
|
+
return await config.onSuccess?.(payload) ?? payload;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export { setupPrecognitionPlus };
|
package/package.json
CHANGED
|
@@ -1,6 +1,61 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "precognition-plus",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Checks common Laravel FormRequest rules in the browser for Precognition forms, and only asks the server for rules that need it.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "CodeNyra",
|
|
7
|
+
"homepage": "https://github.com/codenyra/precognition-plus#readme",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/codenyra/precognition-plus.git",
|
|
11
|
+
"directory": "js"
|
|
12
|
+
},
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/codenyra/precognition-plus/issues"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"main": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"files": [
|
|
21
|
+
"dist"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"build": "tsup",
|
|
31
|
+
"typecheck": "tsc --noEmit",
|
|
32
|
+
"test": "vitest run",
|
|
33
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"laravel-precognition": "^2.1"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@inertiajs/react": "^3.11",
|
|
40
|
+
"@inertiajs/vue3": "^3.11",
|
|
41
|
+
"@types/react": "^19.0",
|
|
42
|
+
"@types/react-dom": "^19.0",
|
|
43
|
+
"jsdom": "^25.0.1",
|
|
44
|
+
"laravel-precognition": "^2.1.1",
|
|
45
|
+
"react": "^19.0",
|
|
46
|
+
"react-dom": "^19.0",
|
|
47
|
+
"tsup": "^8.0",
|
|
48
|
+
"typescript": "^5.6",
|
|
49
|
+
"vitest": "^2.1",
|
|
50
|
+
"vue": "^3.5"
|
|
51
|
+
},
|
|
52
|
+
"keywords": [
|
|
53
|
+
"laravel",
|
|
54
|
+
"inertia",
|
|
55
|
+
"precognition",
|
|
56
|
+
"validation",
|
|
57
|
+
"vue",
|
|
58
|
+
"react",
|
|
59
|
+
"svelte"
|
|
60
|
+
]
|
|
61
|
+
}
|