@adobe/design-data 2.0.2 → 3.0.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adobe/design-data",
3
- "version": "2.0.2",
3
+ "version": "3.0.0",
4
4
  "description": "Node.js helpers for @adobe/design-data-wasm: filesystem dataset loading, token write operations, and authoring-session management",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -43,7 +43,7 @@
43
43
  "dependencies": {
44
44
  "ajv": "^8.17.1",
45
45
  "ajv-formats": "^3.0.1",
46
- "@adobe/design-data-wasm": "0.3.0"
46
+ "@adobe/design-data-wasm": "0.4.0"
47
47
  },
48
48
  "devDependencies": {
49
49
  "ava": "^6.1.2"
package/src/index.js CHANGED
@@ -15,28 +15,9 @@
15
15
  *
16
16
  * - `loadDataset(dir)` — walk *.tokens.json from a directory → Dataset
17
17
  * - `loadDatasetSync(dir, wasm)` — synchronous variant for pre-loaded wasm modules
18
- * - `writeProductContext(opts)` — write/update product-context.json
19
- * - `writeToken(key, token, opts)` — write a token into a target JSON file
20
- * - `buildTokenFromWizard(opts)` — build a token object from authoring-session state
21
- * - `startSession / stepClassification / stepValues / commitSession / cancelSession / getSession / listSessions`
22
- * — on-disk authoring-session state machine (JS port of sdk/core/src/authoring/session.rs)
23
18
  */
24
19
 
25
20
  export { loadDataset, loadDatasetSync } from "./load.js";
26
- export {
27
- writeProductContext,
28
- writeToken,
29
- buildTokenFromWizard,
30
- } from "./write.js";
31
- export {
32
- startSession,
33
- getSession,
34
- listSessions,
35
- stepClassification,
36
- stepValues,
37
- commitSession,
38
- cancelSession,
39
- } from "./session.js";
40
21
  export {
41
22
  validateDataset,
42
23
  validateTokenAgainstSchema,
package/src/session.js DELETED
@@ -1,253 +0,0 @@
1
- // Copyright 2026 Adobe. All rights reserved.
2
- // This file is licensed to you under the Apache License, Version 2.0 (the "License");
3
- // you may not use this file except in compliance with the License. You may obtain a copy
4
- // of the License at http://www.apache.org/licenses/LICENSE-2.0
5
- //
6
- // Unless required by applicable law or agreed to in writing, software distributed under
7
- // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
- // OF ANY KIND, either express or implied. See the License for the specific language
9
- // governing permissions and limitations under the License.
10
-
11
- /**
12
- * On-disk authoring-session store — JS port of sdk/core/src/authoring/session.rs.
13
- *
14
- * Session state is one JSON file per session in the sessions directory, matching
15
- * the file format produced by the Rust CLI so that in-progress sessions started by
16
- * the CLI can be continued here and vice versa.
17
- *
18
- * NOTE: `stepIntent` (the NLP suggestion-ranking step) still delegates to the CLI
19
- * because the `suggest` API is not yet exposed on the wasm surface. All other
20
- * session operations (start, classification, values, commit, cancel, get, list)
21
- * run fully in-process.
22
- */
23
-
24
- import {
25
- readFileSync,
26
- writeFileSync,
27
- mkdirSync,
28
- unlinkSync,
29
- readdirSync,
30
- renameSync,
31
- } from "node:fs";
32
- import { join } from "node:path";
33
- import { randomUUID } from "node:crypto";
34
- import { homedir } from "node:os";
35
- import {
36
- buildTokenFromWizard,
37
- writeToken,
38
- writeProductContext,
39
- } from "./write.js";
40
- import { validateTokenAgainstSchema, resolveSchemaDir } from "./validate.js";
41
-
42
- /**
43
- * Return the directory where session JSON files are stored.
44
- * Mirrors `sessions_dir()` from sdk/core/src/authoring/session.rs.
45
- *
46
- * @returns {string}
47
- */
48
- function sessionsDir() {
49
- if (process.env.DESIGN_DATA_AUTHORING_SESSIONS_DIR) {
50
- return process.env.DESIGN_DATA_AUTHORING_SESSIONS_DIR;
51
- }
52
- let base;
53
- if (process.platform === "win32") {
54
- base = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
55
- } else if (process.platform === "darwin") {
56
- base = join(homedir(), "Library", "Application Support");
57
- } else {
58
- base = process.env.XDG_DATA_HOME ?? join(homedir(), ".local", "share");
59
- }
60
- return join(base, "design-data", "authoring-sessions");
61
- }
62
-
63
- function sessionPath(sessionId) {
64
- return join(sessionsDir(), `${sessionId}.json`);
65
- }
66
-
67
- function atomicWriteSession(draft) {
68
- const dir = sessionsDir();
69
- mkdirSync(dir, { recursive: true });
70
- const tmp =
71
- sessionPath(draft.session_id) + ".tmp." + randomUUID().slice(0, 8);
72
- writeFileSync(tmp, JSON.stringify(draft, null, 2) + "\n", "utf-8");
73
- renameSync(tmp, sessionPath(draft.session_id));
74
- }
75
-
76
- function readSessionOrThrow(sessionId) {
77
- try {
78
- return JSON.parse(readFileSync(sessionPath(sessionId), "utf-8"));
79
- } catch {
80
- throw new Error(`Session not found: ${sessionId}`);
81
- }
82
- }
83
-
84
- /**
85
- * Start a new authoring session.
86
- *
87
- * @param {string} datasetPath - Absolute path to the token dataset directory.
88
- * @returns {{ session_id: string, dataset_path: string, wizard: object }}
89
- */
90
- export function startSession(datasetPath) {
91
- const sessionId = randomUUID();
92
- const draft = {
93
- session_id: sessionId,
94
- dataset_path: datasetPath,
95
- wizard: {
96
- intent: null,
97
- classification: null,
98
- values: null,
99
- },
100
- };
101
- atomicWriteSession(draft);
102
- return draft;
103
- }
104
-
105
- /**
106
- * Get the current state of a session.
107
- *
108
- * @param {string} sessionId
109
- */
110
- export function getSession(sessionId) {
111
- return readSessionOrThrow(sessionId);
112
- }
113
-
114
- /**
115
- * List all active sessions.
116
- *
117
- * @returns {object[]}
118
- */
119
- export function listSessions() {
120
- const dir = sessionsDir();
121
- try {
122
- return readdirSync(dir)
123
- .filter((f) => f.endsWith(".json") && !f.endsWith(".tmp"))
124
- .map((f) => JSON.parse(readFileSync(join(dir, f), "utf-8")));
125
- } catch {
126
- return [];
127
- }
128
- }
129
-
130
- /**
131
- * Update the classification step (layer, property, nameFields).
132
- *
133
- * @param {string} sessionId
134
- * @param {{ layer: string, property: string, nameFields?: Array<{key:string,value:string}> }} opts
135
- * @returns {object} Updated session draft.
136
- */
137
- export function stepClassification(
138
- sessionId,
139
- { layer, property, nameFields = [] },
140
- ) {
141
- const draft = readSessionOrThrow(sessionId);
142
- draft.wizard.classification = { layer, property, nameFields };
143
- atomicWriteSession(draft);
144
- return draft;
145
- }
146
-
147
- /**
148
- * Update the values step (mode-specific literal or alias rows).
149
- *
150
- * @param {string} sessionId
151
- * @param {Array<{mode_combo: string[][], kind: 'Literal'|'Alias', alias_target: string, literal: string}>} rows
152
- * @returns {object} Updated session draft.
153
- */
154
- export function stepValues(sessionId, rows) {
155
- const draft = readSessionOrThrow(sessionId);
156
- draft.wizard.values = rows;
157
- atomicWriteSession(draft);
158
- return draft;
159
- }
160
-
161
- /**
162
- * Commit the session: build the token from wizard state, validate it against its
163
- * JSON Schema (Layer-1), write it to disk, and delete the session file.
164
- *
165
- * @param {object} opts
166
- * @param {string} opts.sessionId
167
- * @param {string} opts.schemaUrl - The `$schema` URL for the token type.
168
- * @param {string} opts.target - Target file path.
169
- * @param {string} [opts.rationale]
170
- * @param {string} [opts.productContext]
171
- * @param {string} [opts.schemaPath] - Path to the schemas/ directory (contains
172
- * token-types/ and token-file.json). Defaults to @adobe/spectrum-tokens schemas.
173
- * Pass an explicit path when working with a custom schema set.
174
- * @param {boolean} [opts.isOverride]
175
- * @returns {{ writtenTo: string, productContextUpdated: boolean, tokenKey: string }}
176
- * @throws {Error} When the built token fails Layer-1 JSON-Schema validation.
177
- */
178
- export function commitSession({
179
- sessionId,
180
- schemaUrl,
181
- target,
182
- rationale,
183
- productContext,
184
- schemaPath,
185
- isOverride = false,
186
- }) {
187
- const draft = readSessionOrThrow(sessionId);
188
-
189
- if (!draft.wizard.classification) {
190
- throw new Error(
191
- `Session ${sessionId} has no classification step — call stepClassification first.`,
192
- );
193
- }
194
- if (!draft.wizard.values || draft.wizard.values.length === 0) {
195
- throw new Error(
196
- `Session ${sessionId} has no values step — call stepValues first.`,
197
- );
198
- }
199
-
200
- const [tokenKey, token] = buildTokenFromWizard({
201
- schemaUrl,
202
- classification: draft.wizard.classification,
203
- rows: draft.wizard.values,
204
- uuid: randomUUID(),
205
- });
206
-
207
- // Layer-1: validate the built token against its JSON Schema before writing.
208
- // Validation runs when a schema directory is available. If schemaPath is
209
- // explicitly provided it must resolve (throws on bad path). If it is omitted
210
- // and auto-discovery finds nothing (e.g. @adobe/spectrum-tokens not installed),
211
- // validation is skipped rather than blocking the commit.
212
- const schemaDir = resolveSchemaDir(schemaPath ?? null, {
213
- required: !!schemaPath,
214
- });
215
- if (schemaDir) {
216
- const validation = validateTokenAgainstSchema(token, schemaDir);
217
- if (!validation.valid) {
218
- const summary = validation.errors.map((e) => e.message).join("; ");
219
- throw new Error(`Token failed JSON-Schema validation: ${summary}`);
220
- }
221
- }
222
-
223
- const result = writeToken(tokenKey, token, {
224
- target,
225
- productContext,
226
- rationale,
227
- isOverride,
228
- });
229
-
230
- // Delete session file after successful commit.
231
- try {
232
- unlinkSync(sessionPath(sessionId));
233
- } catch {
234
- /* already gone */
235
- }
236
-
237
- return { ...result, tokenKey };
238
- }
239
-
240
- /**
241
- * Cancel and delete a session.
242
- *
243
- * @param {string} sessionId
244
- * @returns {{ cancelled: string }}
245
- */
246
- export function cancelSession(sessionId) {
247
- try {
248
- unlinkSync(sessionPath(sessionId));
249
- } catch {
250
- /* already gone — idempotent */
251
- }
252
- return { cancelled: sessionId };
253
- }
package/src/write.js DELETED
@@ -1,179 +0,0 @@
1
- // Copyright 2026 Adobe. All rights reserved.
2
- // This file is licensed to you under the Apache License, Version 2.0 (the "License");
3
- // you may not use this file except in compliance with the License. You may obtain a copy
4
- // of the License at http://www.apache.org/licenses/LICENSE-2.0
5
- //
6
- // Unless required by applicable law or agreed to in writing, software distributed under
7
- // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
8
- // OF ANY KIND, either express or implied. See the License for the specific language
9
- // governing permissions and limitations under the License.
10
-
11
- /**
12
- * Token write helpers — pure Node.js implementations of the CLI's write and
13
- * write-token operations. No native binary required.
14
- *
15
- * These mirror `design-data write` and `design-data write-token` but run
16
- * in-process, with atomic file writes (tmp-then-rename) for safety.
17
- */
18
-
19
- import { readFileSync, writeFileSync, mkdirSync, renameSync } from "node:fs";
20
- import { dirname, resolve } from "node:path";
21
- import { randomUUID } from "node:crypto";
22
-
23
- /**
24
- * Atomically write `content` to `dest` (via a `.tmp` sibling).
25
- *
26
- * @param {string} dest
27
- * @param {string} content
28
- */
29
- function atomicWrite(dest, content) {
30
- const tmp = dest + ".tmp." + randomUUID().slice(0, 8);
31
- mkdirSync(dirname(dest), { recursive: true });
32
- writeFileSync(tmp, content, "utf-8");
33
- renameSync(tmp, dest);
34
- }
35
-
36
- /**
37
- * Write or update a `product-context.json` document.
38
- *
39
- * Mirrors `design-data write --output <path> [--rationale <text>]`.
40
- * Creates the file if absent with the standard `specVersion`/`layer`/`createdBy`
41
- * scaffold; overwrites in place if it already exists.
42
- *
43
- * @param {object} opts
44
- * @param {string} opts.output - Destination file path.
45
- * @param {string} [opts.rationale] - Optional rationale string to embed.
46
- * @returns {string} Confirmation message (matches CLI stdout).
47
- */
48
- export function writeProductContext({ output, rationale } = {}) {
49
- const dest = resolve(output);
50
- let doc;
51
- try {
52
- doc = JSON.parse(readFileSync(dest, "utf-8"));
53
- } catch {
54
- doc = {
55
- specVersion: "1.0.0-draft",
56
- layer: "product",
57
- };
58
- }
59
- if (rationale != null) doc.rationale = rationale;
60
- doc.createdBy = { type: "agent", tool: "design-data" };
61
- doc.createdAt = new Date().toISOString();
62
-
63
- atomicWrite(dest, JSON.stringify(doc, null, 2) + "\n");
64
- return `Wrote ${dest}`;
65
- }
66
-
67
- /**
68
- * Write a single token into a target JSON file.
69
- *
70
- * Mirrors `design-data write-token <key>` (without JSON-Schema validation —
71
- * structural validation requires the schema files, which callers should handle
72
- * at a higher level or via the CLI if strict validation is needed).
73
- *
74
- * The target file is treated as an object-keyed token map (legacy format):
75
- * `{ "<key>": { ...token fields... } }`
76
- * If the file is absent it is created; if it exists the key is merged in.
77
- *
78
- * @param {string} key - Token key, e.g. `"accent-background-color-default"`.
79
- * @param {object} token - The token object to write (must include `$schema`, `uuid`, etc.).
80
- * @param {object} [opts]
81
- * @param {string} opts.target - Target file path.
82
- * @param {string} [opts.productContext] - Optional path to product-context.json to update.
83
- * @param {string} [opts.rationale] - Rationale to embed in the product-context update.
84
- * @param {boolean} [opts.isOverride] - Whether this is a product-layer override.
85
- * @returns {{ writtenTo: string, productContextUpdated: boolean }}
86
- */
87
- export function writeToken(
88
- key,
89
- token,
90
- { target, productContext, rationale, isOverride = false } = {},
91
- ) {
92
- const dest = resolve(target);
93
- let existing;
94
- try {
95
- existing = JSON.parse(readFileSync(dest, "utf-8"));
96
- } catch {
97
- existing = {};
98
- }
99
- existing[key] = token;
100
- atomicWrite(dest, JSON.stringify(existing, null, 2) + "\n");
101
-
102
- let productContextUpdated = false;
103
- if (productContext) {
104
- writeProductContext({ output: productContext, rationale });
105
- productContextUpdated = true;
106
- }
107
-
108
- return { writtenTo: dest, productContextUpdated };
109
- }
110
-
111
- /**
112
- * Build a cascade-format token object from authoring-session wizard state.
113
- *
114
- * Converts the wizard's `rows` (ValueRowInput[]) into either a simple
115
- * `{ value }` token or a `{ sets: { ... } }` multi-mode token.
116
- *
117
- * @param {object} opts
118
- * @param {string} opts.schemaUrl - The `$schema` URL.
119
- * @param {object} opts.classification - `{ layer, property, nameFields }`.
120
- * @param {Array<{mode_combo: string[][], kind: 'Literal'|'Alias', alias_target: string, literal: string}>} opts.rows
121
- * @param {string} opts.uuid - Token UUID.
122
- * @returns {[string, object]} Tuple of [tokenKey, tokenObject].
123
- */
124
- export function buildTokenFromWizard({
125
- schemaUrl,
126
- classification,
127
- rows,
128
- uuid,
129
- }) {
130
- const { layer, property, nameFields = [] } = classification;
131
- const name = { property };
132
- for (const { key, value } of nameFields) name[key] = value;
133
-
134
- const tokenKey = [property, ...nameFields.map(({ value }) => value)].join(
135
- "/",
136
- );
137
-
138
- // Build the value portion from rows.
139
- let tokenValue;
140
- if (rows.length === 1 && rows[0].mode_combo.length === 0) {
141
- // Single base value — simple format.
142
- const row = rows[0];
143
- tokenValue =
144
- row.kind === "Alias"
145
- ? { value: { ref: row.alias_target } }
146
- : { value: row.literal };
147
- } else {
148
- // Multi-mode format: group rows by the first dimension key.
149
- const sets = {};
150
- for (const row of rows) {
151
- let target = sets;
152
- const pairs = row.mode_combo;
153
- for (let i = 0; i < pairs.length; i++) {
154
- const [k, v] = pairs[i];
155
- if (i < pairs.length - 1) {
156
- target[k] = target[k] ?? {};
157
- target = target[k][v] = target[k][v] ?? {};
158
- } else {
159
- target[k] = target[k] ?? {};
160
- target[k][v] =
161
- row.kind === "Alias"
162
- ? { value: { ref: row.alias_target } }
163
- : { value: row.literal };
164
- }
165
- }
166
- }
167
- tokenValue = { sets };
168
- }
169
-
170
- const token = {
171
- $schema: schemaUrl,
172
- uuid: uuid ?? randomUUID(),
173
- name,
174
- layer,
175
- ...tokenValue,
176
- };
177
-
178
- return [tokenKey, token];
179
- }