poad 2.63.0 → 2.65.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/global/start.js +7 -0
- package/package.json +2 -2
- package/poad.js +4 -3
- package/project/auth/import.js +68 -0
- package/project/auth/index.js +7 -0
- package/project/cli.js +7 -2
- package/project/db/import.js +138 -0
- package/project/db/index.js +1 -0
- package/project/deploy.js +22 -0
- package/project/gen/types.js +10 -2
- package/project/logs.js +2 -0
- package/project/source.js +341 -42
- package/project/storage/cp.js +4 -2
- package/project/upgrade.js +10 -0
- package/test/api-exposure.test.js +60 -0
- package/test/auth-import.test.js +113 -0
- package/test/cloud.test.js +1 -0
- package/test/data.test.js +24 -0
- package/test/deps.test.js +108 -0
- package/test/import.test.js +226 -0
- package/test/logs.test.js +12 -0
- package/test/naming.test.js +18 -0
- package/test/source.test.js +116 -0
- package/test/storage-tus.test.js +169 -0
- package/test/storage.test.js +7 -0
- package/utils/api-exposure/api-exposure.sql +42 -0
- package/utils/api-exposure/index.js +97 -0
- package/utils/auth-import.js +204 -0
- package/utils/cloud/bundle.js +16 -2
- package/utils/cloud/deps.js +297 -0
- package/utils/data.js +41 -0
- package/utils/help-details.js +57 -4
- package/utils/import-upload.js +112 -0
- package/utils/logline.js +2 -2
- package/utils/logs.js +8 -1
- package/utils/naming.js +41 -0
- package/utils/runner.js +1 -1
- package/utils/storage-copy.js +31 -3
- package/utils/storage-tus.js +201 -0
- package/utils/storage.js +37 -1
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// poad auth import <fichier> : lecture du fichier de comptes (JSON, JSON Lines,
|
|
2
|
+
// CSV), découpage en lots, envoi au service auth (POST /auth/v1/admin/users/import),
|
|
3
|
+
// bilan. La vérification de chaque ligne (empreinte bcrypt, adresse, dates…)
|
|
4
|
+
// est faite par le service auth, la même que dans la console.
|
|
5
|
+
//
|
|
6
|
+
// Jamais d'empreinte ni de mot de passe dans un message : les erreurs de
|
|
7
|
+
// lecture ne reprennent pas le texte du fichier, et le service n'en renvoie pas.
|
|
8
|
+
const { CloudError, usageError } = require('./cloud/api');
|
|
9
|
+
|
|
10
|
+
/** Lignes par requête (le service en accepte 1000) */
|
|
11
|
+
const BATCH = 500;
|
|
12
|
+
|
|
13
|
+
const parseJson = (text, line) => {
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(text);
|
|
16
|
+
} catch {
|
|
17
|
+
// Le message de JSON.parse cite le texte : il peut contenir une empreinte
|
|
18
|
+
throw usageError(line ? `Invalid JSON on line ${line}.` : 'Invalid JSON.');
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** CSV (RFC 4180) : guillemets, guillemets doublés, retours à la ligne dans un champ ; virgule ou point-virgule */
|
|
23
|
+
function parseCsv(text) {
|
|
24
|
+
const src = text.replace(/^/, '');
|
|
25
|
+
const first = src.split(/\r?\n/, 1)[0] || '';
|
|
26
|
+
const sep = (first.match(/;/g) || []).length > (first.match(/,/g) || []).length ? ';' : ',';
|
|
27
|
+
const out = [];
|
|
28
|
+
let cells = [];
|
|
29
|
+
let cell = '';
|
|
30
|
+
let quoted = false;
|
|
31
|
+
let line = 1;
|
|
32
|
+
let start = 1;
|
|
33
|
+
for (let i = 0; i < src.length; i++) {
|
|
34
|
+
const c = src[i];
|
|
35
|
+
if (quoted) {
|
|
36
|
+
if (c === '"' && src[i + 1] === '"') {
|
|
37
|
+
cell += '"';
|
|
38
|
+
i++;
|
|
39
|
+
} else if (c === '"') quoted = false;
|
|
40
|
+
else {
|
|
41
|
+
if (c === '\n') line++;
|
|
42
|
+
cell += c;
|
|
43
|
+
}
|
|
44
|
+
} else if (c === '"' && cell === '') quoted = true;
|
|
45
|
+
else if (c === sep) {
|
|
46
|
+
cells.push(cell);
|
|
47
|
+
cell = '';
|
|
48
|
+
} else if (c === '\n' || c === '\r') {
|
|
49
|
+
if (c === '\r' && src[i + 1] === '\n') i++;
|
|
50
|
+
cells.push(cell);
|
|
51
|
+
if (cells.some((x) => x !== '')) out.push({ line: start, cells });
|
|
52
|
+
cells = [];
|
|
53
|
+
cell = '';
|
|
54
|
+
line++;
|
|
55
|
+
start = line;
|
|
56
|
+
} else cell += c;
|
|
57
|
+
}
|
|
58
|
+
if (quoted) throw usageError(`Invalid CSV: a quote opened on line ${start} is never closed.`);
|
|
59
|
+
cells.push(cell);
|
|
60
|
+
if (cells.some((x) => x !== '')) out.push({ line: start, cells });
|
|
61
|
+
const [head, ...records] = out;
|
|
62
|
+
return { header: ((head && head.cells) || []).map((h) => h.trim()), records };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Le contenu d'un fichier en comptes : { rows, lines, format }. Format choisi
|
|
67
|
+
* par l'extension (.json, .jsonl/.ndjson, .csv), sinon par le contenu.
|
|
68
|
+
*/
|
|
69
|
+
function parseFile(name, text) {
|
|
70
|
+
const trimmed = String(text).replace(/^/, '').trim();
|
|
71
|
+
if (!trimmed) throw usageError('The file is empty.');
|
|
72
|
+
const lower = String(name).toLowerCase();
|
|
73
|
+
if (lower.endsWith('.jsonl') || lower.endsWith('.ndjson')) {
|
|
74
|
+
const rows = [];
|
|
75
|
+
const lines = [];
|
|
76
|
+
trimmed.split(/\r?\n/).forEach((l, i) => {
|
|
77
|
+
if (!l.trim()) return;
|
|
78
|
+
rows.push(parseJson(l, i + 1));
|
|
79
|
+
lines.push(i + 1);
|
|
80
|
+
});
|
|
81
|
+
return { rows, lines, format: 'jsonl' };
|
|
82
|
+
}
|
|
83
|
+
if (lower.endsWith('.json') || /^[[{]/.test(trimmed)) {
|
|
84
|
+
const data = parseJson(trimmed);
|
|
85
|
+
const list = Array.isArray(data) ? data : data && Array.isArray(data.users) ? data.users : null;
|
|
86
|
+
if (!list) throw usageError('JSON expected: a list of accounts, or an object { "users": [...] }.');
|
|
87
|
+
return { rows: list, lines: list.map((_, i) => i + 1), format: 'json' };
|
|
88
|
+
}
|
|
89
|
+
const { header, records } = parseCsv(trimmed);
|
|
90
|
+
if (!header.includes('email')) throw usageError('CSV expected: a first header line with at least an "email" column.');
|
|
91
|
+
return {
|
|
92
|
+
rows: records.map(({ cells }) => Object.fromEntries(header.map((h, i) => [h, cells[i] === undefined ? '' : cells[i]]).filter(([h, v]) => h && v !== ''))),
|
|
93
|
+
lines: records.map((r) => r.line),
|
|
94
|
+
format: 'csv',
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const emailOf = (row) => (row && typeof row === 'object' ? String(row.email == null ? '' : row.email).trim().toLowerCase() : '');
|
|
99
|
+
|
|
100
|
+
/** Doublons sur tout le fichier (le service ne voit qu'un lot) : la première ligne compte */
|
|
101
|
+
function splitDuplicates({ rows, lines }) {
|
|
102
|
+
const seen = new Set();
|
|
103
|
+
const keep = [];
|
|
104
|
+
const duplicates = [];
|
|
105
|
+
rows.forEach((row, i) => {
|
|
106
|
+
const email = emailOf(row);
|
|
107
|
+
if (email && seen.has(email)) duplicates.push({ line: lines[i], email, status: 'invalid', reason: 'duplicate email in the file' });
|
|
108
|
+
else {
|
|
109
|
+
if (email) seen.add(email);
|
|
110
|
+
keep.push({ row, line: lines[i] });
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
return { keep, duplicates };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function batches(items, size = BATCH) {
|
|
117
|
+
const out = [];
|
|
118
|
+
for (let i = 0; i < items.length; i += size) out.push(items.slice(i, i + size));
|
|
119
|
+
return out;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function summarize(results) {
|
|
123
|
+
const s = { total: results.length, created: 0, would_create: 0, exists: 0, invalid: 0, failed: 0, verified: 0, verified_ignored: 0, confirmations_sent: 0, confirmations_failed: 0, confirmations_to_send: 0 };
|
|
124
|
+
for (const r of results) {
|
|
125
|
+
s[r.status] += 1;
|
|
126
|
+
if (r.verified_ignored) s.verified_ignored += 1;
|
|
127
|
+
if (r.confirmation === 'sent') s.confirmations_sent += 1;
|
|
128
|
+
if (r.confirmation === 'failed') s.confirmations_failed += 1;
|
|
129
|
+
if (r.confirmation === 'would_send') s.confirmations_to_send += 1;
|
|
130
|
+
if ((r.status === 'created' || r.status === 'would_create') && r.email_verified) s.verified += 1;
|
|
131
|
+
}
|
|
132
|
+
return s;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Appel du service auth de la cible (local : clé service_role ; poad.io : jeton
|
|
137
|
+
* court renouvelé une minute avant son expiration, comme poad storage).
|
|
138
|
+
*/
|
|
139
|
+
function authClient({ base, key, apikey, renew }, { fetch: doFetch = fetch, timeout = 120000 } = {}) {
|
|
140
|
+
let auth = { key, apikey: apikey || key, expires: renew && renew.first ? Date.parse(renew.first) : null };
|
|
141
|
+
return async function importBatch(body) {
|
|
142
|
+
if (renew && auth.expires && auth.expires - Date.now() < 60000) {
|
|
143
|
+
const t = await renew.next();
|
|
144
|
+
auth = { key: t.token, apikey: t.anon_key, expires: Date.parse(t.expires_at) };
|
|
145
|
+
}
|
|
146
|
+
let res;
|
|
147
|
+
try {
|
|
148
|
+
res = await doFetch(`${base}/auth/v1/admin/users/import`, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: { apikey: auth.apikey, authorization: `Bearer ${auth.key}`, 'content-type': 'application/json' },
|
|
151
|
+
body: JSON.stringify(body),
|
|
152
|
+
signal: AbortSignal.timeout(timeout),
|
|
153
|
+
});
|
|
154
|
+
} catch (err) {
|
|
155
|
+
throw new CloudError(`The auth service does not answer on ${base}: ${(err && err.cause && err.cause.message) || (err && err.message) || err}`);
|
|
156
|
+
}
|
|
157
|
+
const text = await res.text().catch(() => '');
|
|
158
|
+
let data = null;
|
|
159
|
+
try {
|
|
160
|
+
data = text ? JSON.parse(text) : null;
|
|
161
|
+
} catch {
|
|
162
|
+
data = null;
|
|
163
|
+
}
|
|
164
|
+
if (res.status === 404) throw new CloudError('This engine does not know the import of accounts (auth 0.13.0 or later needed): run "poad upgrade".', { status: 404, code: 'unsupported' });
|
|
165
|
+
if (res.status < 200 || res.status >= 300) {
|
|
166
|
+
const msg = (data && (data.msg || data.message || data.error_description)) || `HTTP ${res.status}`;
|
|
167
|
+
throw new CloudError(`The auth service refused the import: ${msg}`, { status: res.status, code: (data && data.error_code) || `http_${res.status}` });
|
|
168
|
+
}
|
|
169
|
+
return data;
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Examine (dryRun) ou importe le fichier lot par lot. onBatch(done, total)
|
|
175
|
+
* suit l'avancement. Un lot refusé (réseau, droits) marque ses lignes en
|
|
176
|
+
* échec et arrête l'import : relancer reprend sans doublon.
|
|
177
|
+
*/
|
|
178
|
+
async function run(parsed, { send, dryRun = false, trustVerified = false, sendConfirmation = false, onBatch = () => {} }) {
|
|
179
|
+
const { keep, duplicates } = splitDuplicates(parsed);
|
|
180
|
+
const results = [...duplicates];
|
|
181
|
+
let done = 0;
|
|
182
|
+
let stopped = null;
|
|
183
|
+
for (const batch of batches(keep)) {
|
|
184
|
+
if (stopped) {
|
|
185
|
+
for (const b of batch) results.push({ line: b.line, email: emailOf(b.row), status: 'failed', reason: `not sent: ${stopped}` });
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
const out = await send({ users: batch.map((b) => b.row), dry_run: dryRun, trust_verified: trustVerified, send_confirmation: sendConfirmation });
|
|
190
|
+
for (const x of out.results)
|
|
191
|
+
results.push({ line: batch[x.index].line, email: x.email, status: x.status, reason: x.reason, email_verified: x.email_verified, has_password: x.has_password, id: x.id, verified_ignored: x.verified_ignored, confirmation: x.confirmation });
|
|
192
|
+
} catch (err) {
|
|
193
|
+
if (err && err.code === 'unsupported') throw err;
|
|
194
|
+
stopped = err && err.message ? err.message : String(err);
|
|
195
|
+
for (const b of batch) results.push({ line: b.line, email: emailOf(b.row), status: 'failed', reason: stopped });
|
|
196
|
+
}
|
|
197
|
+
done += batch.length;
|
|
198
|
+
onBatch(done, keep.length);
|
|
199
|
+
}
|
|
200
|
+
results.sort((a, b) => a.line - b.line);
|
|
201
|
+
return { results, summary: summarize(results) };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
module.exports = { BATCH, parseCsv, parseFile, splitDuplicates, batches, summarize, authClient, run };
|
package/utils/cloud/bundle.js
CHANGED
|
@@ -194,7 +194,11 @@ function build(poadDir, { limits = LIMITS, exclude = [] } = {}) {
|
|
|
194
194
|
} catch {}
|
|
195
195
|
}
|
|
196
196
|
if (!rels.includes('config.toml')) throw new BundleError('poad/config.toml is missing');
|
|
197
|
-
|
|
197
|
+
// Dépendances npm des fonctions : seuls les fichiers que leurs imports atteignent (utils/cloud/deps.js)
|
|
198
|
+
const deps = require('./deps').traceDependencies(path.join(poadDir, 'functions'));
|
|
199
|
+
const depFiles = deps.files.map((f) => ({ ...f, path: `functions/${f.rel}` }));
|
|
200
|
+
for (const s of skipped) if (s.path === 'functions/node_modules/') s.reason = depFiles.length ? `only the ${depFiles.length} file(s) the functions import are sent` : 'nothing imported by the functions';
|
|
201
|
+
if (rels.length + depFiles.length > limits.maxEntries) throw new BundleError(`more than ${limits.maxEntries} files to send`);
|
|
198
202
|
|
|
199
203
|
const secrets = localSecrets(poadDir);
|
|
200
204
|
const files = [];
|
|
@@ -232,9 +236,19 @@ function build(poadDir, { limits = LIMITS, exclude = [] } = {}) {
|
|
|
232
236
|
if (total > limits.maxBytes) throw new BundleError(`the poad/ folder to send is larger than ${limits.maxBytes} bytes`);
|
|
233
237
|
files.push({ path: rel, data, mode: st.mode & 0o111 ? 0o755 : 0o644 });
|
|
234
238
|
}
|
|
239
|
+
for (const f of depFiles) {
|
|
240
|
+
const st = fs.statSync(f.abs);
|
|
241
|
+
if (st.size > limits.maxFile) throw new BundleError(`${f.path} is larger than ${Math.round(limits.maxFile / 1048576)} MB`);
|
|
242
|
+
const data = f.data || fs.readFileSync(f.abs);
|
|
243
|
+
for (const s of secrets) if (data.includes(s)) throw new BundleError(`${f.path} contains a secret of poad/secrets.toml: nothing was sent.`);
|
|
244
|
+
total += data.length;
|
|
245
|
+
if (total > limits.maxBytes) throw new BundleError(`the poad/ folder to send is larger than ${limits.maxBytes} bytes`);
|
|
246
|
+
// Jamais exécutable : un paquet n'apporte que du code et des données lus par l'engine
|
|
247
|
+
files.push({ path: f.path, data, mode: 0o644 });
|
|
248
|
+
}
|
|
235
249
|
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
236
250
|
const tgz = zlib.gzipSync(tar(files), { level: 9 });
|
|
237
|
-
return { tgz, files: files.map((f) => ({ path: f.path, size: f.data.length })), skipped, bytes: total };
|
|
251
|
+
return { tgz, files: files.map((f) => ({ path: f.path, size: f.data.length })), skipped, bytes: total, deps: { packages: deps.packages, files: depFiles.length, missing: deps.missing, outside: deps.outside } };
|
|
238
252
|
}
|
|
239
253
|
|
|
240
254
|
module.exports = { build, tar, cleanConfig, cleanCredentialsManifest, localSecrets, BundleError, DIRS, FILES, LIMITS };
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
// Dépendances npm des fonctions, pour poad deploy : seuls les fichiers de
|
|
2
|
+
// poad/functions/node_modules que les fonctions atteignent réellement par leurs
|
|
3
|
+
// imports, plus le package.json de chaque paquet atteint (réduit aux champs de la
|
|
4
|
+
// résolution) et les fichiers des règles de modules (.wasm, .bin, .txt, .html, .sql).
|
|
5
|
+
//
|
|
6
|
+
// Même résolution que le service functions de l'engine (services/functions/src/resolve.ts),
|
|
7
|
+
// elle-même alignée sur wrangler pour un Worker de Cloudflare : conditions d'export
|
|
8
|
+
// workerd, worker, browser, puis import / require / default ; champs browser, module,
|
|
9
|
+
// main ; sous-chemins et motifs ; imports « # » du paquet. Les imports sont relevés dans le
|
|
10
|
+
// texte (import, export … from, import(), require()) : un import trouvé dans un commentaire
|
|
11
|
+
// ajoute au pire un fichier de trop, jamais un de moins. Un paquet installé plus haut que
|
|
12
|
+
// poad/functions/node_modules n'est pas envoyé (signalé).
|
|
13
|
+
//
|
|
14
|
+
// traceDependencies('<projet>/poad/functions')
|
|
15
|
+
// → { files: [{ rel, abs, data? }], packages: ['jpeg-js', …], missing: [{ spec, from }], outside: [...] }
|
|
16
|
+
// rel : chemin relatif à poad/functions (« node_modules/jpeg-js/index.js »)
|
|
17
|
+
const fs = require('fs');
|
|
18
|
+
const path = require('path');
|
|
19
|
+
const { builtinModules } = require('module');
|
|
20
|
+
|
|
21
|
+
const SOURCE_EXT = ['.ts', '.tsx', '.mts', '.cts', '.js', '.mjs', '.cjs', '.jsx'];
|
|
22
|
+
const PROBE_EXT = ['.js', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts', '.jsx', '.json'];
|
|
23
|
+
// Règles de modules de Cloudflare (WebAssembly, données, texte) : envoyés, pas lus
|
|
24
|
+
const MODULE_RULE = /\.(wasm|bin|txt|html|sql)(\?module)?$/;
|
|
25
|
+
// Ce qu'un paquet peut contenir d'utile ici (jamais d'exécutable ni de binaire natif)
|
|
26
|
+
const SENT_EXT = /\.(js|mjs|cjs|jsx|ts|tsx|mts|cts|json|wasm|bin|txt|html|sql)$/;
|
|
27
|
+
const NODE = new Set(builtinModules.filter((m) => !m.startsWith('_')));
|
|
28
|
+
const PKG_FIELDS = ['name', 'version', 'type', 'main', 'module', 'browser', 'exports', 'imports', 'sideEffects'];
|
|
29
|
+
const IMPORT_CONDITIONS = ['workerd', 'worker', 'browser', 'import', 'module', 'default'];
|
|
30
|
+
const REQUIRE_CONDITIONS = ['workerd', 'worker', 'browser', 'require', 'default'];
|
|
31
|
+
// Jeux de conditions essayés : celui de l'engine (import ou require), et sans « module » au cas
|
|
32
|
+
// où l'assembleur ne le connaît pas ; un fichier de trop plutôt qu'un de moins
|
|
33
|
+
const CONDITION_SETS = [IMPORT_CONDITIONS, REQUIRE_CONDITIONS, IMPORT_CONDITIONS.filter((c) => c !== 'module')];
|
|
34
|
+
const targetsAll = (map, sub) => new Set(CONDITION_SETS.flatMap((c) => targetsOf(map, sub, c)));
|
|
35
|
+
|
|
36
|
+
/** Imports d'un texte source : [{ spec, kind: 'import' | 'require' }] */
|
|
37
|
+
function importsOf(text) {
|
|
38
|
+
const out = [];
|
|
39
|
+
const add = (spec, kind) => spec && out.push({ spec, kind });
|
|
40
|
+
const res = [
|
|
41
|
+
[/\b(?:import|export)\s+(?:type\s+)?(?:[\w*{}\s,$]+?\s+from\s+)?["']([^"'\n]+)["']/g, 'import'],
|
|
42
|
+
[/\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g, 'import'],
|
|
43
|
+
[/\brequire\s*\(\s*["']([^"'\n]+)["']\s*\)/g, 'require'],
|
|
44
|
+
];
|
|
45
|
+
for (const [re, kind] of res) for (const m of text.matchAll(re)) add(m[1], kind);
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const isFile = (p) => {
|
|
50
|
+
try {
|
|
51
|
+
return fs.statSync(p).isFile();
|
|
52
|
+
} catch {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const isDir = (p) => {
|
|
57
|
+
try {
|
|
58
|
+
return fs.statSync(p).isDirectory();
|
|
59
|
+
} catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const readJson = (p) => {
|
|
64
|
+
try {
|
|
65
|
+
return JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
66
|
+
} catch {
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** Nom du paquet d'un import nu ; null pour un chemin ou un protocole */
|
|
72
|
+
function packageName(spec) {
|
|
73
|
+
if (!spec || spec.startsWith('.') || spec.startsWith('/') || spec.startsWith('#') || /^[a-z][a-z0-9+.-]*:/i.test(spec)) return null;
|
|
74
|
+
const parts = spec.split('/');
|
|
75
|
+
if (spec.startsWith('@')) return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : null;
|
|
76
|
+
return parts[0];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Cible d'un champ exports / imports pour un sous-chemin et des conditions ; toutes les cibles possibles */
|
|
80
|
+
function targetsOf(map, sub, conditions) {
|
|
81
|
+
const pick = (t, star) => {
|
|
82
|
+
if (typeof t === 'string') return [star === undefined ? t : t.split('*').join(star)];
|
|
83
|
+
if (Array.isArray(t)) {
|
|
84
|
+
for (const x of t) {
|
|
85
|
+
const r = pick(x, star);
|
|
86
|
+
if (r.length) return r;
|
|
87
|
+
}
|
|
88
|
+
return [];
|
|
89
|
+
}
|
|
90
|
+
if (t && typeof t === 'object') {
|
|
91
|
+
for (const [k, v] of Object.entries(t)) if (conditions.includes(k)) {
|
|
92
|
+
const r = pick(v, star);
|
|
93
|
+
if (r.length) return r;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return [];
|
|
97
|
+
};
|
|
98
|
+
// exports : une chaîne, un tableau, ou un objet de conditions, valent pour « . »
|
|
99
|
+
if (typeof map === 'string' || Array.isArray(map)) return sub === '.' ? pick(map) : [];
|
|
100
|
+
if (!map || typeof map !== 'object') return [];
|
|
101
|
+
const keys = Object.keys(map);
|
|
102
|
+
if (keys.length && !keys.some((k) => k.startsWith('.') || k.startsWith('#'))) return sub === '.' ? pick(map) : [];
|
|
103
|
+
if (Object.prototype.hasOwnProperty.call(map, sub)) return pick(map[sub]);
|
|
104
|
+
// Motifs « ./x/* » : le préfixe le plus long l'emporte
|
|
105
|
+
let best = null;
|
|
106
|
+
for (const k of keys) {
|
|
107
|
+
const i = k.indexOf('*');
|
|
108
|
+
if (i < 0) continue;
|
|
109
|
+
const pre = k.slice(0, i);
|
|
110
|
+
const post = k.slice(i + 1);
|
|
111
|
+
if (sub.startsWith(pre) && sub.endsWith(post) && sub.length >= pre.length + post.length && (!best || pre.length > best.pre.length)) best = { k, pre, star: sub.slice(pre.length, sub.length - post.length) };
|
|
112
|
+
}
|
|
113
|
+
if (best) return pick(map[best.k], best.star);
|
|
114
|
+
// Ancienne forme « ./dossier/ »
|
|
115
|
+
for (const k of keys) if (k.endsWith('/') && sub.startsWith(k) && typeof map[k] === 'string') return [map[k] + sub.slice(k.length)];
|
|
116
|
+
return [];
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Trace les dépendances des fonctions de functionsDir. N'envoie que ce qui est sous
|
|
121
|
+
* functionsDir/node_modules.
|
|
122
|
+
*/
|
|
123
|
+
function traceDependencies(functionsDir) {
|
|
124
|
+
const root = path.resolve(functionsDir);
|
|
125
|
+
const nm = path.join(root, 'node_modules');
|
|
126
|
+
const result = { files: [], packages: [], missing: [], outside: [] };
|
|
127
|
+
if (!isDir(root)) return result;
|
|
128
|
+
const inNm = (p) => p === nm || p.startsWith(nm + path.sep);
|
|
129
|
+
const sent = new Map();
|
|
130
|
+
const pkgs = new Map();
|
|
131
|
+
const seen = new Set();
|
|
132
|
+
const queue = [];
|
|
133
|
+
|
|
134
|
+
const send = (abs) => {
|
|
135
|
+
if (!inNm(abs) || sent.has(abs)) return;
|
|
136
|
+
const rel = path.relative(root, abs).split(path.sep).join('/');
|
|
137
|
+
if (!SENT_EXT.test(rel) || rel.split('/').some((s) => s.startsWith('.'))) return;
|
|
138
|
+
sent.set(abs, { rel, abs });
|
|
139
|
+
};
|
|
140
|
+
// package.json d'un paquet atteint, réduit aux champs de la résolution
|
|
141
|
+
const sendPkg = (dir) => {
|
|
142
|
+
const file = path.join(dir, 'package.json');
|
|
143
|
+
if (!inNm(dir) || sent.has(file)) return;
|
|
144
|
+
const pkg = readJson(file);
|
|
145
|
+
if (!pkg) return;
|
|
146
|
+
const slim = {};
|
|
147
|
+
for (const k of PKG_FIELDS) if (pkg[k] !== undefined) slim[k] = pkg[k];
|
|
148
|
+
sent.set(file, { rel: path.relative(root, file).split(path.sep).join('/'), abs: file, data: Buffer.from(JSON.stringify(slim, null, 2) + '\n') });
|
|
149
|
+
if (pkg.name && !pkgs.has(pkg.name)) pkgs.set(pkg.name, dir);
|
|
150
|
+
// Champ browser en objet : ses remplacements peuvent être atteints
|
|
151
|
+
if (pkg.browser && typeof pkg.browser === 'object') {
|
|
152
|
+
for (const v of Object.values(pkg.browser)) {
|
|
153
|
+
if (typeof v !== 'string') continue;
|
|
154
|
+
if (v.startsWith('.')) visitPath(path.join(dir, v), 'import');
|
|
155
|
+
else visitBare(v, dir, 'import', dir);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
const visit = (abs, kind) => {
|
|
160
|
+
if (seen.has(abs)) return;
|
|
161
|
+
seen.add(abs);
|
|
162
|
+
send(abs);
|
|
163
|
+
if (MODULE_RULE.test(abs) || abs.endsWith('.json')) return;
|
|
164
|
+
if (SOURCE_EXT.includes(path.extname(abs))) queue.push({ abs, kind });
|
|
165
|
+
};
|
|
166
|
+
/** Fichier (ou dossier) désigné par un chemin : mêmes essais qu'un assembleur */
|
|
167
|
+
const fileOf = (p) => {
|
|
168
|
+
if (isFile(p)) return p;
|
|
169
|
+
for (const e of PROBE_EXT) if (isFile(p + e)) return p + e;
|
|
170
|
+
// Source TypeScript importée en « .js »
|
|
171
|
+
if (/\.[mc]?js$/.test(p)) for (const e of ['.ts', '.tsx', '.mts', '.cts']) if (isFile(p.replace(/\.[mc]?js$/, e))) return p.replace(/\.[mc]?js$/, e);
|
|
172
|
+
if (isDir(p)) {
|
|
173
|
+
const pkg = readJson(path.join(p, 'package.json'));
|
|
174
|
+
if (pkg) {
|
|
175
|
+
sendPkg(p);
|
|
176
|
+
for (const f of [typeof pkg.browser === 'string' ? pkg.browser : null, pkg.module, pkg.main].filter((x) => typeof x === 'string')) {
|
|
177
|
+
const hit = fileOf(path.join(p, f));
|
|
178
|
+
if (hit) return hit;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
for (const e of PROBE_EXT) if (isFile(path.join(p, 'index' + e))) return path.join(p, 'index' + e);
|
|
182
|
+
}
|
|
183
|
+
return null;
|
|
184
|
+
};
|
|
185
|
+
const visitPath = (p, kind) => {
|
|
186
|
+
const f = fileOf(p.replace(/\?module$/, ''));
|
|
187
|
+
if (f) visit(f, kind);
|
|
188
|
+
return f;
|
|
189
|
+
};
|
|
190
|
+
/** Dossier du paquet name, vu depuis from (node_modules de from et de ses parents, jusqu'à poad/functions) */
|
|
191
|
+
const packageDir = (name, from) => {
|
|
192
|
+
for (let d = from; ; d = path.dirname(d)) {
|
|
193
|
+
const cand = path.join(d, 'node_modules', name);
|
|
194
|
+
if (isDir(cand)) return cand;
|
|
195
|
+
if (d === root || path.dirname(d) === d || !d.startsWith(root)) break;
|
|
196
|
+
}
|
|
197
|
+
// Plus haut que poad/functions : trouvé mais pas envoyé
|
|
198
|
+
for (let d = path.dirname(root); path.dirname(d) !== d; d = path.dirname(d)) if (isDir(path.join(d, 'node_modules', name))) return { outside: path.join(d, 'node_modules', name) };
|
|
199
|
+
return null;
|
|
200
|
+
};
|
|
201
|
+
const entriesOf = (dir, sub, kind) => {
|
|
202
|
+
const pkg = readJson(path.join(dir, 'package.json')) || {};
|
|
203
|
+
sendPkg(dir);
|
|
204
|
+
const hits = [];
|
|
205
|
+
if (pkg.exports !== undefined) {
|
|
206
|
+
// Les deux jeux de conditions : un paquet importé puis requis ailleurs garde ses deux formes
|
|
207
|
+
const targets = targetsAll(pkg.exports, sub);
|
|
208
|
+
for (const t of targets) if (typeof t === 'string' && t.startsWith('./')) hits.push(path.join(dir, t));
|
|
209
|
+
if (hits.length) return hits;
|
|
210
|
+
}
|
|
211
|
+
if (sub !== '.') return [path.join(dir, sub)];
|
|
212
|
+
// Sans exports : tous les champs d'entrée présents (un de trop vaut mieux qu'un de moins)
|
|
213
|
+
for (const f of [typeof pkg.browser === 'string' ? pkg.browser : null, pkg.module, pkg.main]) if (typeof f === 'string') hits.push(path.join(dir, f));
|
|
214
|
+
if (!hits.length) hits.push(path.join(dir, 'index'));
|
|
215
|
+
return hits;
|
|
216
|
+
};
|
|
217
|
+
const visitBare = (spec, fromDir, kind, importer) => {
|
|
218
|
+
const name = packageName(spec);
|
|
219
|
+
if (!name) return true;
|
|
220
|
+
const dir = packageDir(name, fromDir);
|
|
221
|
+
if (!dir) return false;
|
|
222
|
+
if (dir.outside) {
|
|
223
|
+
if (!result.outside.includes(name)) result.outside.push(name);
|
|
224
|
+
return true;
|
|
225
|
+
}
|
|
226
|
+
const sub = spec === name ? '.' : `./${spec.slice(name.length + 1)}`;
|
|
227
|
+
for (const t of entriesOf(dir, sub, kind)) visitPath(t, kind);
|
|
228
|
+
return true;
|
|
229
|
+
};
|
|
230
|
+
/** Import « #x » : champ imports du package.json le plus proche */
|
|
231
|
+
const visitHash = (spec, fromDir, kind) => {
|
|
232
|
+
for (let d = fromDir; d.startsWith(root); d = path.dirname(d)) {
|
|
233
|
+
const pkg = readJson(path.join(d, 'package.json'));
|
|
234
|
+
if (!pkg) continue;
|
|
235
|
+
sendPkg(d);
|
|
236
|
+
for (const t of targetsAll(pkg.imports, spec)) {
|
|
237
|
+
if (typeof t !== 'string') continue;
|
|
238
|
+
if (t.startsWith('./')) visitPath(path.join(d, t), kind);
|
|
239
|
+
else visitBare(t, d, kind, d);
|
|
240
|
+
}
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// Les sources des fonctions (hors node_modules et dossiers cachés)
|
|
246
|
+
const walk = (d) => {
|
|
247
|
+
let entries = [];
|
|
248
|
+
try {
|
|
249
|
+
entries = fs.readdirSync(d, { withFileTypes: true });
|
|
250
|
+
} catch {
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
for (const e of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
254
|
+
if (e.name === 'node_modules' || e.name.startsWith('.')) continue;
|
|
255
|
+
const p = path.join(d, e.name);
|
|
256
|
+
if (e.isDirectory()) walk(p);
|
|
257
|
+
else if (e.isFile() && SOURCE_EXT.includes(path.extname(e.name))) queue.push({ abs: p, kind: 'import', own: true });
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
walk(root);
|
|
261
|
+
|
|
262
|
+
while (queue.length) {
|
|
263
|
+
const { abs, own } = queue.shift();
|
|
264
|
+
let text;
|
|
265
|
+
try {
|
|
266
|
+
text = fs.readFileSync(abs, 'utf8');
|
|
267
|
+
} catch {
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
const from = path.dirname(abs);
|
|
271
|
+
for (const { spec, kind } of importsOf(text)) {
|
|
272
|
+
const clean = spec.replace(/\?module$/, '');
|
|
273
|
+
if (clean === '@poadio/functions' || /^(node|cloudflare|data|https?):/.test(clean)) continue;
|
|
274
|
+
if (clean.startsWith('./') || clean.startsWith('../') || clean === '.' || clean === '..') {
|
|
275
|
+
visitPath(path.resolve(from, clean), kind);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
if (clean.startsWith('#')) {
|
|
279
|
+
visitHash(clean, from, kind);
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
const name = packageName(clean);
|
|
283
|
+
if (!name) continue;
|
|
284
|
+
const ok = visitBare(clean, from, kind, abs);
|
|
285
|
+
// Module de Node.js sans paquet de ce nom : fourni par le moteur (nodejs_compat)
|
|
286
|
+
if (!ok && !NODE.has(clean) && !NODE.has(name) && own) {
|
|
287
|
+
const rel = path.relative(root, abs).split(path.sep).join('/');
|
|
288
|
+
if (!result.missing.some((m) => m.spec === name)) result.missing.push({ spec: name, from: rel });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
result.files = [...sent.values()].sort((a, b) => (a.rel < b.rel ? -1 : 1));
|
|
293
|
+
result.packages = [...pkgs.keys()].sort();
|
|
294
|
+
return result;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
module.exports = { traceDependencies, importsOf, targetsOf, packageName };
|
package/utils/data.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Service data de l'engine (/rest/v1) : réglages de poad/config.toml passés en
|
|
2
|
+
// variables d'environnement par `poad start`.
|
|
3
|
+
//
|
|
4
|
+
// [data]
|
|
5
|
+
// service_role_statement_timeout = 120 délai d'une requête de service_role (fonction
|
|
6
|
+
// avec poadAdmin, flow, script) : secondes, ou
|
|
7
|
+
// "500ms", "30s", "2min", "1h" ; 0 = sans limite
|
|
8
|
+
//
|
|
9
|
+
// anon (3 s) et authenticated (8 s) ne se règlent pas ici. La passerelle de l'engine attend la
|
|
10
|
+
// réponse de data et functions aussi longtemps pour une requête portant la clé service_role
|
|
11
|
+
// (POAD_GATEWAY_SERVICE_ROLE_TIMEOUT : 15 min au plus, 0 = ce plafond), 60 s pour les autres. Engine avec data 0.11.0 et
|
|
12
|
+
// plus (POAD_DATA_STATEMENT_TIMEOUT_SERVICE_ROLE) ; un engine plus ancien ignore la
|
|
13
|
+
// variable et coupe toutes les requêtes à 8 s.
|
|
14
|
+
|
|
15
|
+
const DURATION = /^(\d+)(ms|s|min|h)?$/;
|
|
16
|
+
const UNIT_MS = { ms: 1, s: 1000, min: 60000, h: 3600000 };
|
|
17
|
+
const MAX_MS = 24 * 3600000;
|
|
18
|
+
|
|
19
|
+
/** Délai normalisé (« 120s », « 500ms », « 0 ») ; { value: null } sans réglage ; warning si refusé */
|
|
20
|
+
const serviceRoleTimeout = (config) => {
|
|
21
|
+
const raw = config && config.data ? config.data.service_role_statement_timeout : undefined;
|
|
22
|
+
if (raw === undefined || raw === null || raw === '') return { value: null };
|
|
23
|
+
const text = String(raw).trim().toLowerCase();
|
|
24
|
+
const m = DURATION.exec(text);
|
|
25
|
+
const ms = m ? Number(m[1]) * UNIT_MS[m[2] || 's'] : NaN;
|
|
26
|
+
if (m && Number.isSafeInteger(ms) && ms <= MAX_MS) return { value: `${m[1]}${m[2] || 's'}` };
|
|
27
|
+
return {
|
|
28
|
+
value: null,
|
|
29
|
+
warning: `[data] service_role_statement_timeout = "${String(raw).slice(0, 32)}" in poad/config.toml is not a duration (examples: 120, "30s", "2min"; 0 = no limit; 24 h at most): the engine default (120 s) is used.`,
|
|
30
|
+
};
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/** Variables de l'engine */
|
|
34
|
+
const engineEnv = (config) => {
|
|
35
|
+
const t = serviceRoleTimeout(config);
|
|
36
|
+
// La passerelle attend la réponse aussi longtemps pour une requête portant la clé service_role
|
|
37
|
+
// (vers data et functions ; 15 min au plus, 0 = ce plafond ; jamais moins de 60 s)
|
|
38
|
+
return t.value === null ? [] : [`POAD_DATA_STATEMENT_TIMEOUT_SERVICE_ROLE=${t.value}`, `POAD_GATEWAY_SERVICE_ROLE_TIMEOUT=${t.value}`];
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
module.exports = { serviceRoleTimeout, engineEnv };
|