UNPKG

10.2 kBJavaScriptView Raw
1'use strict';
2
3const Assert = require('@hapi/hoek/lib/assert');
4const Clone = require('@hapi/hoek/lib/clone');
5const Reach = require('@hapi/hoek/lib/reach');
6
7const Common = require('./common');
8
9let Template;
10
11
12const internals = {
13 symbol: Symbol('ref'), // Used to internally identify references (shared with other joi versions)
14 defaults: {
15 adjust: null,
16 in: false,
17 iterables: null,
18 map: null,
19 separator: '.',
20 type: 'value'
21 }
22};
23
24
25exports.create = function (key, options = {}) {
26
27 Assert(typeof key === 'string', 'Invalid reference key:', key);
28 Common.assertOptions(options, ['adjust', 'ancestor', 'in', 'iterables', 'map', 'prefix', 'separator']);
29 Assert(!options.prefix || typeof options.prefix === 'object', 'options.prefix must be of type object');
30
31 const ref = Object.assign({}, internals.defaults, options);
32 delete ref.prefix;
33
34 const separator = ref.separator;
35 const context = internals.context(key, separator, options.prefix);
36 ref.type = context.type;
37 key = context.key;
38
39 if (ref.type === 'value') {
40 if (context.root) {
41 Assert(!separator || key[0] !== separator, 'Cannot specify relative path with root prefix');
42 ref.ancestor = 'root';
43 if (!key) {
44 key = null;
45 }
46 }
47
48 if (separator &&
49 separator === key) {
50
51 key = null;
52 ref.ancestor = 0;
53 }
54 else {
55 if (ref.ancestor !== undefined) {
56 Assert(!separator || !key || key[0] !== separator, 'Cannot combine prefix with ancestor option');
57 }
58 else {
59 const [ancestor, slice] = internals.ancestor(key, separator);
60 if (slice) {
61 key = key.slice(slice);
62 if (key === '') {
63 key = null;
64 }
65 }
66
67 ref.ancestor = ancestor;
68 }
69 }
70 }
71
72 ref.path = separator ? (key === null ? [] : key.split(separator)) : [key];
73
74 return new internals.Ref(ref);
75};
76
77
78exports.in = function (key, options = {}) {
79
80 return exports.create(key, Object.assign({}, options, { in: true }));
81};
82
83
84exports.isRef = function (ref) {
85
86 return ref ? !!ref[Common.symbols.ref] : false;
87};
88
89
90internals.Ref = class {
91
92 constructor(options) {
93
94 Assert(typeof options === 'object', 'Invalid reference construction');
95 Common.assertOptions(options, [
96 'adjust', 'ancestor', 'in', 'iterables', 'map', 'path', 'separator', 'type', // Copied
97 'depth', 'key', 'root', 'display' // Overridden
98 ]);
99
100 Assert([false, undefined].includes(options.separator) || typeof options.separator === 'string' && options.separator.length === 1, 'Invalid separator');
101 Assert(!options.adjust || typeof options.adjust === 'function', 'options.adjust must be a function');
102 Assert(!options.map || Array.isArray(options.map), 'options.map must be an array');
103 Assert(!options.map || !options.adjust, 'Cannot set both map and adjust options');
104
105 Object.assign(this, internals.defaults, options);
106
107 Assert(this.type === 'value' || this.ancestor === undefined, 'Non-value references cannot reference ancestors');
108
109 if (Array.isArray(this.map)) {
110 this.map = new Map(this.map);
111 }
112
113 this.depth = this.path.length;
114 this.key = this.path.length ? this.path.join(this.separator) : null;
115 this.root = this.path[0];
116
117 this.updateDisplay();
118 }
119
120 resolve(value, state, prefs, local, options = {}) {
121
122 Assert(!this.in || options.in, 'Invalid in() reference usage');
123
124 if (this.type === 'global') {
125 return this._resolve(prefs.context, state, options);
126 }
127
128 if (this.type === 'local') {
129 return this._resolve(local, state, options);
130 }
131
132 if (!this.ancestor) {
133 return this._resolve(value, state, options);
134 }
135
136 if (this.ancestor === 'root') {
137 return this._resolve(state.ancestors[state.ancestors.length - 1], state, options);
138 }
139
140 Assert(this.ancestor <= state.ancestors.length, 'Invalid reference exceeds the schema root:', this.display);
141 return this._resolve(state.ancestors[this.ancestor - 1], state, options);
142 }
143
144 _resolve(target, state, options) {
145
146 let resolved;
147
148 if (this.type === 'value' &&
149 state.mainstay.shadow &&
150 options.shadow !== false) {
151
152 resolved = state.mainstay.shadow.get(this.absolute(state));
153 }
154
155 if (resolved === undefined) {
156 resolved = Reach(target, this.path, { iterables: this.iterables, functions: true });
157 }
158
159 if (this.adjust) {
160 resolved = this.adjust(resolved);
161 }
162
163 if (this.map) {
164 const mapped = this.map.get(resolved);
165 if (mapped !== undefined) {
166 resolved = mapped;
167 }
168 }
169
170 if (state.mainstay) {
171 state.mainstay.tracer.resolve(state, this, resolved);
172 }
173
174 return resolved;
175 }
176
177 toString() {
178
179 return this.display;
180 }
181
182 absolute(state) {
183
184 return [...state.path.slice(0, -this.ancestor), ...this.path];
185 }
186
187 clone() {
188
189 return new internals.Ref(this);
190 }
191
192 describe() {
193
194 const ref = { path: this.path };
195
196 if (this.type !== 'value') {
197 ref.type = this.type;
198 }
199
200 if (this.separator !== '.') {
201 ref.separator = this.separator;
202 }
203
204 if (this.type === 'value' &&
205 this.ancestor !== 1) {
206
207 ref.ancestor = this.ancestor;
208 }
209
210 if (this.map) {
211 ref.map = [...this.map];
212 }
213
214 for (const key of ['adjust', 'iterables']) {
215 if (this[key] !== null) {
216 ref[key] = this[key];
217 }
218 }
219
220 if (this.in !== false) {
221 ref.in = true;
222 }
223
224 return { ref };
225 }
226
227 updateDisplay() {
228
229 const key = this.key !== null ? this.key : '';
230 if (this.type !== 'value') {
231 this.display = `ref:${this.type}:${key}`;
232 return;
233 }
234
235 if (!this.separator) {
236 this.display = `ref:${key}`;
237 return;
238 }
239
240 if (!this.ancestor) {
241 this.display = `ref:${this.separator}${key}`;
242 return;
243 }
244
245 if (this.ancestor === 'root') {
246 this.display = `ref:root:${key}`;
247 return;
248 }
249
250 if (this.ancestor === 1) {
251 this.display = `ref:${key || '..'}`;
252 return;
253 }
254
255 const lead = new Array(this.ancestor + 1).fill(this.separator).join('');
256 this.display = `ref:${lead}${key || ''}`;
257 }
258};
259
260
261internals.Ref.prototype[Common.symbols.ref] = true;
262
263
264exports.build = function (desc) {
265
266 desc = Object.assign({}, internals.defaults, desc);
267 if (desc.type === 'value' &&
268 desc.ancestor === undefined) {
269
270 desc.ancestor = 1;
271 }
272
273 return new internals.Ref(desc);
274};
275
276
277internals.context = function (key, separator, prefix = {}) {
278
279 key = key.trim();
280
281 if (prefix) {
282 const globalp = prefix.global === undefined ? '$' : prefix.global;
283 if (globalp !== separator &&
284 key.startsWith(globalp)) {
285
286 return { key: key.slice(globalp.length), type: 'global' };
287 }
288
289 const local = prefix.local === undefined ? '#' : prefix.local;
290 if (local !== separator &&
291 key.startsWith(local)) {
292
293 return { key: key.slice(local.length), type: 'local' };
294 }
295
296 const root = prefix.root === undefined ? '/' : prefix.root;
297 if (root !== separator &&
298 key.startsWith(root)) {
299
300 return { key: key.slice(root.length), type: 'value', root: true };
301 }
302 }
303
304 return { key, type: 'value' };
305};
306
307
308internals.ancestor = function (key, separator) {
309
310 if (!separator) {
311 return [1, 0]; // 'a_b' -> 1 (parent)
312 }
313
314 if (key[0] !== separator) { // 'a.b' -> 1 (parent)
315 return [1, 0];
316 }
317
318 if (key[1] !== separator) { // '.a.b' -> 0 (self)
319 return [0, 1];
320 }
321
322 let i = 2;
323 while (key[i] === separator) {
324 ++i;
325 }
326
327 return [i - 1, i]; // '...a.b.' -> 2 (grandparent)
328};
329
330
331exports.toSibling = 0;
332
333exports.toParent = 1;
334
335
336exports.Manager = class {
337
338 constructor() {
339
340 this.refs = []; // 0: [self refs], 1: [parent refs], 2: [grandparent refs], ...
341 }
342
343 register(source, target) {
344
345 if (!source) {
346 return;
347 }
348
349 target = target === undefined ? exports.toParent : target;
350
351 // Array
352
353 if (Array.isArray(source)) {
354 for (const ref of source) {
355 this.register(ref, target);
356 }
357
358 return;
359 }
360
361 // Schema
362
363 if (Common.isSchema(source)) {
364 for (const item of source._refs.refs) {
365 if (item.ancestor - target >= 0) {
366 this.refs.push({ ancestor: item.ancestor - target, root: item.root });
367 }
368 }
369
370 return;
371 }
372
373 // Reference
374
375 if (exports.isRef(source) &&
376 source.type === 'value' &&
377 source.ancestor - target >= 0) {
378
379 this.refs.push({ ancestor: source.ancestor - target, root: source.root });
380 }
381
382 // Template
383
384 Template = Template || require('./template');
385
386 if (Template.isTemplate(source)) {
387 this.register(source.refs(), target);
388 }
389 }
390
391 get length() {
392
393 return this.refs.length;
394 }
395
396 clone() {
397
398 const copy = new exports.Manager();
399 copy.refs = Clone(this.refs);
400 return copy;
401 }
402
403 reset() {
404
405 this.refs = [];
406 }
407
408 roots() {
409
410 return this.refs.filter((ref) => !ref.ancestor).map((ref) => ref.root);
411 }
412};