@things-factory/survey 0.0.0-stage → 10.1.316

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.
Files changed (81) hide show
  1. package/dist-client/index.d.ts +1 -0
  2. package/dist-client/index.js +2 -0
  3. package/dist-client/pages/my-surveys.d.ts +24 -0
  4. package/dist-client/pages/my-surveys.js +256 -0
  5. package/dist-client/pages/survey-editor.d.ts +62 -0
  6. package/dist-client/pages/survey-editor.js +668 -0
  7. package/dist-client/pages/survey-list.d.ts +15 -0
  8. package/dist-client/pages/survey-list.js +150 -0
  9. package/dist-client/pages/survey-trustee.d.ts +21 -0
  10. package/dist-client/pages/survey-trustee.js +170 -0
  11. package/dist-client/route.d.ts +1 -0
  12. package/dist-client/route.js +17 -0
  13. package/dist-client/utils/survey-api.d.ts +16 -0
  14. package/dist-client/utils/survey-api.js +46 -0
  15. package/dist-client/utils/survey-result.d.ts +4 -0
  16. package/dist-client/utils/survey-result.js +79 -0
  17. package/dist-client/utils/survey-secret.d.ts +40 -0
  18. package/dist-client/utils/survey-secret.js +154 -0
  19. package/dist-server/index.d.ts +2 -0
  20. package/dist-server/index.js +27 -0
  21. package/dist-server/role-tasks.d.ts +2 -0
  22. package/dist-server/role-tasks.js +16 -0
  23. package/dist-server/service/index.d.ts +16 -0
  24. package/dist-server/service/index.js +30 -0
  25. package/dist-server/service/refusal.d.ts +57 -0
  26. package/dist-server/service/refusal.js +66 -0
  27. package/dist-server/service/survey/ballot-route.d.ts +1 -0
  28. package/dist-server/service/survey/ballot-route.js +30 -0
  29. package/dist-server/service/survey/ballot-worker.d.ts +1 -0
  30. package/dist-server/service/survey/ballot-worker.js +19 -0
  31. package/dist-server/service/survey/index.d.ts +10 -0
  32. package/dist-server/service/survey/index.js +14 -0
  33. package/dist-server/service/survey/survey-answer.d.ts +23 -0
  34. package/dist-server/service/survey/survey-answer.js +99 -0
  35. package/dist-server/service/survey/survey-attributes.d.ts +16 -0
  36. package/dist-server/service/survey/survey-attributes.js +39 -0
  37. package/dist-server/service/survey/survey-ballot.d.ts +14 -0
  38. package/dist-server/service/survey/survey-ballot.js +61 -0
  39. package/dist-server/service/survey/survey-class-key.d.ts +20 -0
  40. package/dist-server/service/survey/survey-class-key.js +92 -0
  41. package/dist-server/service/survey/survey-question.d.ts +27 -0
  42. package/dist-server/service/survey/survey-question.js +113 -0
  43. package/dist-server/service/survey/survey-resolver.d.ts +37 -0
  44. package/dist-server/service/survey/survey-resolver.js +492 -0
  45. package/dist-server/service/survey/survey-respondent.d.ts +17 -0
  46. package/dist-server/service/survey/survey-respondent.js +81 -0
  47. package/dist-server/service/survey/survey-rules.d.ts +169 -0
  48. package/dist-server/service/survey/survey-rules.js +299 -0
  49. package/dist-server/service/survey/survey-secret.d.ts +133 -0
  50. package/dist-server/service/survey/survey-secret.js +347 -0
  51. package/dist-server/service/survey/survey-service.d.ts +83 -0
  52. package/dist-server/service/survey/survey-service.js +384 -0
  53. package/dist-server/service/survey/survey-trustee.d.ts +25 -0
  54. package/dist-server/service/survey/survey-trustee.js +119 -0
  55. package/dist-server/service/survey/survey-types.d.ts +91 -0
  56. package/dist-server/service/survey/survey-types.js +319 -0
  57. package/dist-server/service/survey/survey.d.ts +47 -0
  58. package/dist-server/service/survey/survey.js +214 -0
  59. package/dist-shared/ballot.d.ts +54 -0
  60. package/dist-shared/ballot.js +146 -0
  61. package/dist-shared/blind-rsa.d.ts +18 -0
  62. package/dist-shared/blind-rsa.js +127 -0
  63. package/dist-shared/elgamal.d.ts +20 -0
  64. package/dist-shared/elgamal.js +54 -0
  65. package/dist-shared/group.d.ts +22 -0
  66. package/dist-shared/group.js +112 -0
  67. package/dist-shared/proofs.d.ts +20 -0
  68. package/dist-shared/proofs.js +94 -0
  69. package/dist-shared/threshold.d.ts +39 -0
  70. package/dist-shared/threshold.js +98 -0
  71. package/dist-shared/verify.d.ts +13 -0
  72. package/dist-shared/verify.js +73 -0
  73. package/package.json +63 -4
  74. package/things-factory.config.js +15 -0
  75. package/translations/en.json +202 -0
  76. package/translations/es.json +202 -0
  77. package/translations/ja.json +202 -0
  78. package/translations/ko.json +202 -0
  79. package/translations/ms.json +202 -0
  80. package/translations/zh.json +202 -0
  81. package/README.md +0 -3
@@ -0,0 +1,169 @@
1
+ /** 기명 · 비밀 (charter decision 10). The level is chosen before opening and never changes after. */
2
+ export declare const SURVEY_LEVELS: readonly ["NAMED", "SECRET"];
3
+ export type SurveyLevel = (typeof SURVEY_LEVELS)[number];
4
+ /** A survey's steps (design §2-1). KEYING and DECRYPTING belong to the secret level. */
5
+ export declare const SURVEY_STATUSES: readonly ["DRAFT", "KEYING", "OPEN", "CLOSED", "DECRYPTING", "COUNTED", "PUBLISHED", "CANCELLED"];
6
+ export type SurveyStatus = (typeof SURVEY_STATUSES)[number];
7
+ /** Question kinds whose answers can be counted - and, at the secret level, proven valid - without reading them (charter §4-4). */
8
+ export declare const QUESTION_KINDS: readonly ["SINGLE", "MULTI", "SCALE", "ALLOCATE"];
9
+ export type QuestionKind = (typeof QUESTION_KINDS)[number];
10
+ /** Who reads a published result - chosen when the survey is made (design §2-1). */
11
+ export declare const RESULT_READERS: readonly ["RESPONDENTS", "OPERATORS"];
12
+ export type ResultReaders = (typeof RESULT_READERS)[number];
13
+ /** The smallest group a published figure may come from at the secret level (charter decision 7). */
14
+ export declare const SECRET_MIN_GROUP = 5;
15
+ export interface QuestionOption {
16
+ key: string;
17
+ label: string;
18
+ }
19
+ export interface QuestionFacts {
20
+ id?: string;
21
+ seq: number;
22
+ kind: QuestionKind | string;
23
+ prompt?: string | null;
24
+ options?: QuestionOption[] | null;
25
+ maxPicks?: number | null;
26
+ scaleMin?: number | null;
27
+ scaleMax?: number | null;
28
+ allocateTotal?: number | null;
29
+ }
30
+ /** An answer to one question - the shape follows its kind. */
31
+ export type AnswerValue = {
32
+ pick?: string;
33
+ picks?: string[];
34
+ value?: number;
35
+ shares?: Record<string, number>;
36
+ };
37
+ export type Problem = {
38
+ code: string;
39
+ params?: Record<string, string | number | boolean | null>;
40
+ };
41
+ /** Why a question cannot stand as written, or nothing. */
42
+ export declare function questionProblem(one: QuestionFacts): Problem | undefined;
43
+ /** Why `value` is not an answer to `one`, or nothing. Every question is answered - none is skipped. */
44
+ export declare function answerProblem(one: QuestionFacts, value: AnswerValue | null | undefined): Problem | undefined;
45
+ /** The steps an operator takes, and where each may start from (design §3). */
46
+ declare const STEPS: Record<string, readonly SurveyStatus[]>;
47
+ export type SurveyStep = keyof typeof STEPS;
48
+ /** Why `step` cannot be taken from `status`, or nothing. */
49
+ export declare function stepRefusal(step: SurveyStep, status: string): Problem | undefined;
50
+ export interface OpeningFacts {
51
+ level: string;
52
+ questions: QuestionFacts[];
53
+ audienceCount: number;
54
+ closesAt?: Date | string | null;
55
+ resultReaders?: string | null;
56
+ }
57
+ /** Why a draft cannot open now, or nothing - the questions stand, someone is asked, it closes later, its readers are chosen. */
58
+ export declare function openingProblem(survey: OpeningFacts, now?: Date): Problem | undefined;
59
+ /** One respondent's answers, with the rate of their weight class (1 when the survey is not weighted). */
60
+ export interface CountedResponse {
61
+ rate: number;
62
+ answers: Record<string, AnswerValue>;
63
+ }
64
+ /** One question's count: per option (SINGLE · MULTI · ALLOCATE) or per value (SCALE), and the sum of the values. */
65
+ export interface QuestionCount {
66
+ questionId: string;
67
+ seq: number;
68
+ kind: string;
69
+ counts: Record<string, number>;
70
+ sum?: number;
71
+ }
72
+ export interface SurveyCount {
73
+ responded: number;
74
+ unweighted: QuestionCount[];
75
+ weighted?: QuestionCount[];
76
+ }
77
+ /** The count of a survey - unweighted always, weighted too when any rate is not 1 (charter §4-5). */
78
+ export declare function countOf(questions: readonly (QuestionFacts & {
79
+ id: string;
80
+ })[], responses: readonly CountedResponse[]): SurveyCount;
81
+ /** One place of a ranked question - its choice, its rank, and its figure when figures are published. */
82
+ export interface TopPlace {
83
+ key: string;
84
+ rank: number;
85
+ value?: number;
86
+ }
87
+ export interface PublishedQuestion extends QuestionCount {
88
+ /** With `publishTop`: the top places alone; `counts` is then left out. */
89
+ top?: TopPlace[];
90
+ }
91
+ export interface Publication {
92
+ responded: number;
93
+ /** Nothing is shown when fewer answered than the smallest group allowed. */
94
+ withheld: boolean;
95
+ figure?: 'WEIGHTED' | 'UNWEIGHTED';
96
+ questions?: PublishedQuestion[];
97
+ }
98
+ /** The figures the survey publishes - weighted or not (design §4); the same set ranks the next round (design §7). */
99
+ export declare function figuresOf(count: SurveyCount, figure?: string | null): {
100
+ figure: 'WEIGHTED' | 'UNWEIGHTED';
101
+ questions: QuestionCount[];
102
+ };
103
+ /** The choices of a question from the highest figure down, each with its competition rank (two firsts, then a third). */
104
+ export declare function ranked(count: QuestionCount, exclude?: ReadonlySet<string>): TopPlace[];
105
+ /**
106
+ * The top k choices of a question, or why they cannot be named: a tie across the k-th place leaves who is in the top k
107
+ * to a rule not yet decided (CEO charter Q16), so it is refused rather than broken here.
108
+ */
109
+ export declare function topOf(count: QuestionCount, k: number, exclude?: ReadonlySet<string>): {
110
+ top?: TopPlace[];
111
+ problem?: Problem;
112
+ };
113
+ /**
114
+ * The figures that may be published (design §4): none when fewer answered than `minGroup`; otherwise one set per
115
+ * question - weighted or unweighted, never both, so that the two cannot be subtracted into a class's own count
116
+ * (charter §4-7 point 3). With `top` (CEO decision 19 - round 1 publishes its top 2 only) a question with choices
117
+ * publishes its top places alone, with or without their figures; the rest stay in the operators' count.
118
+ */
119
+ export declare function publishable(count: SurveyCount, settings: {
120
+ minGroup?: number | null;
121
+ figure?: string | null;
122
+ top?: number | null;
123
+ topFigures?: boolean | null;
124
+ }): Publication & {
125
+ problem?: Problem;
126
+ };
127
+ /**
128
+ * The choices a next round takes from the round before (design §7): the top k of its first question among those not
129
+ * withdrawn, reaching no further down than `depth` - a finalist who withdraws is followed by the 3rd, then the 4th
130
+ * (CEO decisions 18 · 20). Read from the round's count, published or not - the one place a carry-over reads beyond
131
+ * what was published (CEO decision 19 publishes the top 2 alone).
132
+ */
133
+ export declare function carriedOf(count: SurveyCount, figure: string | null | undefined, k: number, withdrawn: readonly string[], depth?: number | null): {
134
+ keys?: string[];
135
+ problem?: Problem;
136
+ };
137
+ /** Whether the survey's close time has come. */
138
+ export declare const closeDue: (survey: {
139
+ status: string;
140
+ closesAt?: Date | string | null;
141
+ }, now?: Date) => boolean;
142
+ /** One condition on an attribute - true or false, at least a number, or below one. */
143
+ export interface WeightCondition {
144
+ attribute: string;
145
+ equals?: boolean | string | number | null;
146
+ atLeast?: number | null;
147
+ below?: number | null;
148
+ }
149
+ export interface WeightClass {
150
+ key: string;
151
+ label?: string;
152
+ when: WeightCondition[];
153
+ rate: number;
154
+ }
155
+ export interface Weighting {
156
+ classes: WeightClass[];
157
+ }
158
+ /** Why a weighting cannot stand, or nothing: classes with distinct keys, whole rates of one or more, known attributes, a class that takes everyone last. */
159
+ export declare function weightingProblem(weighting: Weighting | null | undefined, known: readonly string[]): Problem | undefined;
160
+ /** The first class whose conditions all hold for one person's attribute values (design §5-1). */
161
+ export declare function classOf(weighting: Weighting, values: Record<string, unknown>): string | undefined;
162
+ /**
163
+ * Why the classes as filled cannot open, or nothing: every class that has anyone in it holds at least `minGroup` - a
164
+ * class is itself something that names people, so the smallest group applies to it before any ballot (charter §4-2).
165
+ */
166
+ export declare function classSizeProblem(sizes: Record<string, number>, minGroup?: number | null): Problem | undefined;
167
+ /** Full years from a hire day to a basis day - both YYYY-MM-DD; nothing when either is missing or the hire comes later. */
168
+ export declare function fullYearsBetween(from?: string | null, to?: string | null): number | undefined;
169
+ export {};
@@ -0,0 +1,299 @@
1
+ "use strict";
2
+ /*
3
+ * The survey's rules (operato-survey design §2 · §3 · §4) - what a question may be, what an answer to it may be, which
4
+ * step a survey may take from where it stands, how the answers are counted, and which figures may be published.
5
+ *
6
+ * Pure - tested without a database. survey-service.ts reads the records these are asked about.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.closeDue = exports.SECRET_MIN_GROUP = exports.RESULT_READERS = exports.QUESTION_KINDS = exports.SURVEY_STATUSES = exports.SURVEY_LEVELS = void 0;
10
+ exports.questionProblem = questionProblem;
11
+ exports.answerProblem = answerProblem;
12
+ exports.stepRefusal = stepRefusal;
13
+ exports.openingProblem = openingProblem;
14
+ exports.countOf = countOf;
15
+ exports.figuresOf = figuresOf;
16
+ exports.ranked = ranked;
17
+ exports.topOf = topOf;
18
+ exports.publishable = publishable;
19
+ exports.carriedOf = carriedOf;
20
+ exports.weightingProblem = weightingProblem;
21
+ exports.classOf = classOf;
22
+ exports.classSizeProblem = classSizeProblem;
23
+ exports.fullYearsBetween = fullYearsBetween;
24
+ /** 기명 · 비밀 (charter decision 10). The level is chosen before opening and never changes after. */
25
+ exports.SURVEY_LEVELS = ['NAMED', 'SECRET'];
26
+ /** A survey's steps (design §2-1). KEYING and DECRYPTING belong to the secret level. */
27
+ exports.SURVEY_STATUSES = ['DRAFT', 'KEYING', 'OPEN', 'CLOSED', 'DECRYPTING', 'COUNTED', 'PUBLISHED', 'CANCELLED'];
28
+ /** Question kinds whose answers can be counted - and, at the secret level, proven valid - without reading them (charter §4-4). */
29
+ exports.QUESTION_KINDS = ['SINGLE', 'MULTI', 'SCALE', 'ALLOCATE'];
30
+ /** Who reads a published result - chosen when the survey is made (design §2-1). */
31
+ exports.RESULT_READERS = ['RESPONDENTS', 'OPERATORS'];
32
+ /** The smallest group a published figure may come from at the secret level (charter decision 7). */
33
+ exports.SECRET_MIN_GROUP = 5;
34
+ const isInt = (value) => typeof value === 'number' && Number.isInteger(value);
35
+ /** Why a question cannot stand as written, or nothing. */
36
+ function questionProblem(one) {
37
+ const at = { seq: one.seq };
38
+ if (!String(one.prompt ?? '').trim())
39
+ return { code: 'survey-question-prompt-required', params: at };
40
+ if (!exports.QUESTION_KINDS.includes(one.kind))
41
+ return { code: 'survey-question-kind-unknown', params: { ...at, kind: String(one.kind) } };
42
+ if (one.kind === 'SCALE') {
43
+ if (!isInt(one.scaleMin) || !isInt(one.scaleMax) || one.scaleMin >= one.scaleMax)
44
+ return { code: 'survey-question-scale-invalid', params: at };
45
+ return undefined;
46
+ }
47
+ const options = one.options ?? [];
48
+ if (options.length < 2)
49
+ return { code: 'survey-question-options-too-few', params: at };
50
+ const keys = options.map(option => String(option?.key ?? '').trim());
51
+ if (keys.some(key => !key) || options.some(option => !String(option?.label ?? '').trim()))
52
+ return { code: 'survey-question-option-blank', params: at };
53
+ if (new Set(keys).size !== keys.length)
54
+ return { code: 'survey-question-option-duplicate', params: at };
55
+ if (one.kind === 'MULTI' && (!isInt(one.maxPicks) || one.maxPicks < 1 || one.maxPicks > options.length)) {
56
+ return { code: 'survey-question-max-picks-invalid', params: { ...at, options: options.length } };
57
+ }
58
+ if (one.kind === 'ALLOCATE' && (!isInt(one.allocateTotal) || one.allocateTotal < 1))
59
+ return { code: 'survey-question-total-invalid', params: at };
60
+ return undefined;
61
+ }
62
+ /** Why `value` is not an answer to `one`, or nothing. Every question is answered - none is skipped. */
63
+ function answerProblem(one, value) {
64
+ const at = { seq: one.seq };
65
+ if (!value)
66
+ return { code: 'survey-answer-missing', params: at };
67
+ const keys = new Set((one.options ?? []).map(option => option.key));
68
+ switch (one.kind) {
69
+ case 'SINGLE':
70
+ return value.pick && keys.has(value.pick) ? undefined : { code: 'survey-answer-invalid', params: at };
71
+ case 'MULTI': {
72
+ const picks = value.picks ?? [];
73
+ if (!picks.length || picks.length > (one.maxPicks ?? 0))
74
+ return { code: 'survey-answer-invalid', params: at };
75
+ if (new Set(picks).size !== picks.length || picks.some(pick => !keys.has(pick)))
76
+ return { code: 'survey-answer-invalid', params: at };
77
+ return undefined;
78
+ }
79
+ case 'SCALE':
80
+ return isInt(value.value) && value.value >= (one.scaleMin ?? 0) && value.value <= (one.scaleMax ?? 0) ? undefined : { code: 'survey-answer-invalid', params: at };
81
+ case 'ALLOCATE': {
82
+ const shares = value.shares ?? {};
83
+ const entries = Object.entries(shares);
84
+ if (entries.some(([key, share]) => !keys.has(key) || !isInt(share) || share < 0))
85
+ return { code: 'survey-answer-invalid', params: at };
86
+ const sum = entries.reduce((total, [, share]) => total + share, 0);
87
+ return sum === one.allocateTotal ? undefined : { code: 'survey-answer-invalid', params: at };
88
+ }
89
+ }
90
+ return { code: 'survey-answer-invalid', params: at };
91
+ }
92
+ /** The steps an operator takes, and where each may start from (design §3). */
93
+ const STEPS = {
94
+ edit: ['DRAFT'],
95
+ open: ['DRAFT', 'KEYING'],
96
+ close: ['OPEN'],
97
+ count: ['CLOSED', 'DECRYPTING'],
98
+ publish: ['COUNTED'],
99
+ cancel: ['DRAFT', 'KEYING', 'OPEN', 'CLOSED', 'DECRYPTING', 'COUNTED'],
100
+ delete: ['DRAFT']
101
+ };
102
+ /** Why `step` cannot be taken from `status`, or nothing. */
103
+ function stepRefusal(step, status) {
104
+ return STEPS[step].includes(status) ? undefined : { code: 'survey-step-not-now', params: { step, status } };
105
+ }
106
+ /** Why a draft cannot open now, or nothing - the questions stand, someone is asked, it closes later, its readers are chosen. */
107
+ function openingProblem(survey, now = new Date()) {
108
+ if (!exports.SURVEY_LEVELS.includes(survey.level))
109
+ return { code: 'survey-level-unknown', params: { level: String(survey.level) } };
110
+ if (!survey.questions.length)
111
+ return { code: 'survey-no-questions' };
112
+ for (const one of survey.questions) {
113
+ const problem = questionProblem(one);
114
+ if (problem)
115
+ return problem;
116
+ }
117
+ if (!exports.RESULT_READERS.includes(String(survey.resultReaders)))
118
+ return { code: 'survey-readers-required' };
119
+ if (!survey.closesAt || new Date(survey.closesAt).getTime() <= now.getTime())
120
+ return { code: 'survey-closes-at-past' };
121
+ if (survey.audienceCount < 1)
122
+ return { code: 'survey-nobody-asked' };
123
+ return undefined;
124
+ }
125
+ function countOne(one, responses, weighted) {
126
+ const counts = {};
127
+ let sum = 0;
128
+ if (one.kind === 'SCALE')
129
+ for (let value = one.scaleMin ?? 0; value <= (one.scaleMax ?? -1); value++)
130
+ counts[String(value)] = 0;
131
+ else
132
+ for (const option of one.options ?? [])
133
+ counts[option.key] = 0;
134
+ for (const response of responses) {
135
+ const by = weighted ? response.rate : 1;
136
+ const value = response.answers[one.id];
137
+ if (!value)
138
+ continue;
139
+ switch (one.kind) {
140
+ case 'SINGLE':
141
+ if (value.pick in counts)
142
+ counts[value.pick] += by;
143
+ break;
144
+ case 'MULTI':
145
+ for (const pick of value.picks ?? [])
146
+ if (pick in counts)
147
+ counts[pick] += by;
148
+ break;
149
+ case 'SCALE':
150
+ counts[String(value.value)] = (counts[String(value.value)] ?? 0) + by;
151
+ sum += (value.value ?? 0) * by;
152
+ break;
153
+ case 'ALLOCATE':
154
+ for (const [key, share] of Object.entries(value.shares ?? {}))
155
+ if (key in counts)
156
+ counts[key] += share * by;
157
+ break;
158
+ }
159
+ }
160
+ return { questionId: one.id, seq: one.seq, kind: one.kind, counts, ...(one.kind === 'SCALE' ? { sum } : {}) };
161
+ }
162
+ /** The count of a survey - unweighted always, weighted too when any rate is not 1 (charter §4-5). */
163
+ function countOf(questions, responses) {
164
+ const ordered = [...questions].sort((a, b) => a.seq - b.seq);
165
+ const weighting = responses.some(one => one.rate !== 1);
166
+ return {
167
+ responded: responses.length,
168
+ unweighted: ordered.map(one => countOne(one, responses, false)),
169
+ ...(weighting ? { weighted: ordered.map(one => countOne(one, responses, true)) } : {})
170
+ };
171
+ }
172
+ /** The figures the survey publishes - weighted or not (design §4); the same set ranks the next round (design §7). */
173
+ function figuresOf(count, figure) {
174
+ const weighted = !!count.weighted?.length && figure === 'WEIGHTED';
175
+ return { figure: weighted ? 'WEIGHTED' : 'UNWEIGHTED', questions: (weighted ? count.weighted : count.unweighted) ?? [] };
176
+ }
177
+ /** The choices of a question from the highest figure down, each with its competition rank (two firsts, then a third). */
178
+ function ranked(count, exclude = new Set()) {
179
+ const rows = Object.entries(count.counts)
180
+ .filter(([key]) => !exclude.has(key))
181
+ .sort((a, b) => b[1] - a[1]);
182
+ return rows.map(([key, value]) => ({ key, value, rank: 1 + rows.filter(([, other]) => other > value).length }));
183
+ }
184
+ /**
185
+ * The top k choices of a question, or why they cannot be named: a tie across the k-th place leaves who is in the top k
186
+ * to a rule not yet decided (CEO charter Q16), so it is refused rather than broken here.
187
+ */
188
+ function topOf(count, k, exclude = new Set()) {
189
+ const rows = ranked(count, exclude);
190
+ if (rows.length < k)
191
+ return { problem: { code: 'survey-top-too-few', params: { seq: count.seq, k, left: rows.length } } };
192
+ if (rows.length > k && rows[k - 1].value === rows[k].value)
193
+ return { problem: { code: 'survey-top-tie', params: { seq: count.seq, k } } };
194
+ return { top: rows.slice(0, k) };
195
+ }
196
+ /**
197
+ * The figures that may be published (design §4): none when fewer answered than `minGroup`; otherwise one set per
198
+ * question - weighted or unweighted, never both, so that the two cannot be subtracted into a class's own count
199
+ * (charter §4-7 point 3). With `top` (CEO decision 19 - round 1 publishes its top 2 only) a question with choices
200
+ * publishes its top places alone, with or without their figures; the rest stay in the operators' count.
201
+ */
202
+ function publishable(count, settings) {
203
+ if (settings.minGroup && count.responded < settings.minGroup)
204
+ return { responded: count.responded, withheld: true };
205
+ const { figure, questions } = figuresOf(count, settings.figure);
206
+ if (!settings.top)
207
+ return { responded: count.responded, withheld: false, figure, questions };
208
+ const out = [];
209
+ for (const one of questions) {
210
+ if (one.kind === 'SCALE') {
211
+ out.push(one);
212
+ continue;
213
+ }
214
+ const { top, problem } = topOf(one, settings.top);
215
+ if (problem)
216
+ return { responded: count.responded, withheld: true, problem };
217
+ out.push({ questionId: one.questionId, seq: one.seq, kind: one.kind, counts: {}, top: top.map(place => (settings.topFigures ? place : { key: place.key, rank: place.rank })) });
218
+ }
219
+ return { responded: count.responded, withheld: false, figure, questions: out };
220
+ }
221
+ /**
222
+ * The choices a next round takes from the round before (design §7): the top k of its first question among those not
223
+ * withdrawn, reaching no further down than `depth` - a finalist who withdraws is followed by the 3rd, then the 4th
224
+ * (CEO decisions 18 · 20). Read from the round's count, published or not - the one place a carry-over reads beyond
225
+ * what was published (CEO decision 19 publishes the top 2 alone).
226
+ */
227
+ function carriedOf(count, figure, k, withdrawn, depth) {
228
+ const first = [...figuresOf(count, figure).questions].sort((a, b) => a.seq - b.seq)[0];
229
+ if (!first || first.kind === 'SCALE')
230
+ return { problem: { code: 'survey-carry-no-choices' } };
231
+ const all = ranked(first);
232
+ const reachable = depth ? all.filter(place => place.rank <= depth) : all;
233
+ const allowed = new Set(reachable.map(place => place.key));
234
+ const exclude = new Set([...Object.keys(first.counts).filter(key => !allowed.has(key)), ...withdrawn]);
235
+ const { top, problem } = topOf(first, k, exclude);
236
+ if (problem)
237
+ return { problem: problem.code === 'survey-top-too-few' ? { code: 'survey-succession-exhausted', params: { depth: depth ?? 0 } } : problem };
238
+ return { keys: top.map(place => place.key) };
239
+ }
240
+ /** Whether the survey's close time has come. */
241
+ const closeDue = (survey, now = new Date()) => survey.status === 'OPEN' && !!survey.closesAt && new Date(survey.closesAt).getTime() <= now.getTime();
242
+ exports.closeDue = closeDue;
243
+ /** Why a weighting cannot stand, or nothing: classes with distinct keys, whole rates of one or more, known attributes, a class that takes everyone last. */
244
+ function weightingProblem(weighting, known) {
245
+ if (!weighting)
246
+ return undefined;
247
+ const classes = weighting.classes ?? [];
248
+ if (classes.length < 2)
249
+ return { code: 'survey-weight-classes-too-few' };
250
+ const keys = classes.map(one => String(one?.key ?? '').trim());
251
+ if (keys.some(key => !key) || new Set(keys).size !== keys.length)
252
+ return { code: 'survey-weight-class-key-invalid' };
253
+ for (const one of classes) {
254
+ if (!isInt(one.rate) || one.rate < 1)
255
+ return { code: 'survey-weight-rate-invalid', params: { class: one.key } };
256
+ for (const condition of one.when ?? []) {
257
+ if (!known.includes(condition.attribute))
258
+ return { code: 'survey-weight-attribute-unknown', params: { class: one.key, attribute: String(condition.attribute) } };
259
+ const kinds = [condition.equals !== undefined && condition.equals !== null, typeof condition.atLeast === 'number', typeof condition.below === 'number'].filter(Boolean).length;
260
+ if (kinds !== 1)
261
+ return { code: 'survey-weight-condition-invalid', params: { class: one.key } };
262
+ }
263
+ }
264
+ if ((classes[classes.length - 1].when ?? []).length)
265
+ return { code: 'survey-weight-last-class-open' };
266
+ return undefined;
267
+ }
268
+ const holds = (condition, value) => {
269
+ if (condition.equals !== undefined && condition.equals !== null)
270
+ return value === condition.equals;
271
+ if (typeof condition.atLeast === 'number')
272
+ return typeof value === 'number' && value >= condition.atLeast;
273
+ if (typeof condition.below === 'number')
274
+ return typeof value === 'number' && value < condition.below;
275
+ return false;
276
+ };
277
+ /** The first class whose conditions all hold for one person's attribute values (design §5-1). */
278
+ function classOf(weighting, values) {
279
+ return weighting.classes.find(one => (one.when ?? []).every(condition => holds(condition, values[condition.attribute])))?.key;
280
+ }
281
+ /**
282
+ * Why the classes as filled cannot open, or nothing: every class that has anyone in it holds at least `minGroup` - a
283
+ * class is itself something that names people, so the smallest group applies to it before any ballot (charter §4-2).
284
+ */
285
+ function classSizeProblem(sizes, minGroup) {
286
+ if (!minGroup)
287
+ return undefined;
288
+ const small = Object.entries(sizes).find(([, size]) => size > 0 && size < minGroup);
289
+ return small ? { code: 'survey-weight-class-small', params: { class: small[0], size: small[1], min: minGroup } } : undefined;
290
+ }
291
+ /** Full years from a hire day to a basis day - both YYYY-MM-DD; nothing when either is missing or the hire comes later. */
292
+ function fullYearsBetween(from, to) {
293
+ if (!from || !to || from > to)
294
+ return undefined;
295
+ const [fy, fm, fd] = from.split('-').map(Number);
296
+ const [ty, tm, td] = to.split('-').map(Number);
297
+ return ty - fy - (tm < fm || (tm === fm && td < fd) ? 1 : 0);
298
+ }
299
+ //# sourceMappingURL=survey-rules.js.map
@@ -0,0 +1,133 @@
1
+ import { EntityManager } from 'typeorm';
2
+ import { Domain } from '@things-factory/shell';
3
+ import { Survey } from './survey';
4
+ import { SurveyTrustee } from './survey-trustee';
5
+ type Who = {
6
+ id: string;
7
+ };
8
+ /** The class name of an unweighted secret survey - one token key for everyone. */
9
+ export declare const ALL = "ALL";
10
+ export declare const keyingContext: (survey: {
11
+ id: string;
12
+ }) => string;
13
+ export declare const ballotContext: (survey: {
14
+ id: string;
15
+ }, serial: string) => string;
16
+ export declare const tallyContext: (survey: {
17
+ id: string;
18
+ }) => string;
19
+ /** A secret draft starts its key: its key holders are named; the questions are fixed from here on. */
20
+ export declare function startKeying(tx: EntityManager, domain: Domain, user: Who, id: string, now?: Date): Promise<Survey>;
21
+ /** A key holder's transport key - shares for them are sealed to it. */
22
+ export declare function postTransportKey(tx: EntityManager, domain: Domain, user: Who, id: string, key: string, proof: any): Promise<SurveyTrustee>;
23
+ /** A key holder's dealing: their commitments and a sealed share for every key holder - once all have transport keys. */
24
+ export declare function postDealing(tx: EntityManager, domain: Domain, user: Who, id: string, dealing: {
25
+ commitments: string[];
26
+ proof: any;
27
+ }, sealed: Record<string, {
28
+ u: string;
29
+ v: string;
30
+ }>): Promise<SurveyTrustee>;
31
+ /** A key holder says every share sealed to them matched its dealer's commitments - their browser checked. */
32
+ export declare function confirmShares(tx: EntityManager, domain: Domain, user: Who, id: string): Promise<SurveyTrustee>;
33
+ /** Opens a keyed secret survey: its key is the key holders' together; each class gets its own token key. */
34
+ export declare function openSecret(tx: EntityManager, domain: Domain, user: Who, survey: Survey, now: Date): Promise<void>;
35
+ export interface BallotKit {
36
+ surveyId: string;
37
+ publicKey: string;
38
+ weightClass: string;
39
+ modulus: string;
40
+ exponent: string;
41
+ taken: boolean;
42
+ }
43
+ /** What a person's browser needs to seal a ballot: the survey's key, their class and its token key. */
44
+ export declare function ballotKitOf(tx: EntityManager, domain: Domain, user: Who, id: string): Promise<BallotKit>;
45
+ /** Signs a person's blinded token - once. The server sees the blinded value only; it never learns the serial. */
46
+ export declare function issueBallot(tx: EntityManager, domain: Domain, user: Who, id: string, blinded: string, now?: Date): Promise<string>;
47
+ export interface BallotSubmission {
48
+ surveyId: string;
49
+ weightClass: string;
50
+ serial: string;
51
+ signature: string;
52
+ sealed: any;
53
+ }
54
+ /**
55
+ * A ballot that comes in without a sign-in (design §6-4): the token's signature under its class's key, a serial not used
56
+ * before, every proof - then kept, and its receipt returned. Sent twice, the same ballot answers with the same receipt.
57
+ */
58
+ export declare function acceptBallot(tx: EntityManager, domain: Partial<Domain>, submission: BallotSubmission, now?: Date): Promise<string>;
59
+ /**
60
+ * Fixes the bulletin and multiplies its ballots into one sum per cell - weighted or not, as the survey publishes - then
61
+ * waits for the key holders. No class may hold more ballots than tokens were issued to it.
62
+ */
63
+ export declare function beginSecretCount(tx: EntityManager, domain: Domain, user: Who, survey: Survey): Promise<void>;
64
+ /** A key holder's partial decryptions of every sum, each with its proof - checked against their verification key. */
65
+ export declare function postPartials(tx: EntityManager, domain: Domain, user: Who, id: string, partials: any[][]): Promise<Survey>;
66
+ /** Everything the count can be checked from - ciphertexts, proofs, keys, sums and partials; no person. */
67
+ export declare function bulletinOf(tx: EntityManager, domain: Domain, id: string): Promise<{
68
+ surveyId: string;
69
+ publicKey: string;
70
+ threshold: number;
71
+ trustees: {
72
+ seq: number;
73
+ status: string;
74
+ transportKey: string;
75
+ dealing: any;
76
+ partials: any;
77
+ }[];
78
+ classKeys: {
79
+ weightClass: string;
80
+ modulus: string;
81
+ exponent: string;
82
+ }[];
83
+ questions: {
84
+ id: any;
85
+ kind: any;
86
+ options: any;
87
+ maxPicks: any;
88
+ scaleMin: any;
89
+ scaleMax: any;
90
+ allocateTotal: any;
91
+ }[];
92
+ ballots: {
93
+ weightClass: string;
94
+ serial: string;
95
+ signature: string;
96
+ sealed: any;
97
+ receipt: string;
98
+ }[];
99
+ facts: any;
100
+ sums: any;
101
+ bulletinHash: string;
102
+ result: any;
103
+ }>;
104
+ /** Whether a receipt is on the survey's ballots - a person checks their own without seeing the others. */
105
+ export declare function receiptListed(tx: EntityManager, domain: Domain, id: string, receipt: string): Promise<boolean>;
106
+ /** A key holder's own view: the survey's key-making facts, and every share sealed to them. */
107
+ export declare function trusteeViewOf(tx: EntityManager, domain: Domain, user: Who, id: string): Promise<{
108
+ surveyId: string;
109
+ name: string;
110
+ status: string;
111
+ threshold: number;
112
+ seq: number;
113
+ myStatus: string;
114
+ trustees: {
115
+ seq: number;
116
+ status: string;
117
+ transportKey: string;
118
+ commitments: any;
119
+ }[];
120
+ sharesForMe: {
121
+ dealer: number;
122
+ sealed: any;
123
+ }[];
124
+ sums: any;
125
+ }>;
126
+ export declare function myTrusteeSurveys(tx: EntityManager, domain: Domain, user: Who): Promise<{
127
+ surveyId: string;
128
+ name: string;
129
+ status: string;
130
+ myStatus: string;
131
+ seq: number;
132
+ }[]>;
133
+ export {};