核心命令行指令
python3 -m http.server 8000
node test_minimal_suite.js
Engine API One-Liners
const t = new TDTtranslator(); await t.initialized; t.processData();
t.translate(raw, scheme, level, opts)
Regex Constants
/^[0-9A-Fa-f]+$/
/^[01]+$/
Defaults & Deep-Links
0 • GCP: 7 (6–12) • Stem: https://id.gs1.orgTechnical Purpose & GS1 Standards Enforced
#The GS1 TDS / TDT 2.3 Translator is a high-throughput, client-side bidirectional conversion and validation engine for GS1 identification keys. It bridges the gap between physical carrier representations (RFID bitstreams, barcode strings) and digital network identifiers (URIs and web resolvers).
GS1 规范性标准 Implemented
| Standard / Specification | Version | Normative Clauses & Core Responsibility |
|---|---|---|
| GS1 Tag Data Standard (TDS) | 2.3 (Ratified & Published) |
Section 14.5.16: Custom Hostname / Domain Compaction (7-bit ASCII with optimizations vs. URN Code 40). Section 14.5 Table F: Compaction methods for GS1 Application Identifiers (numeric, alphanumeric, date formats, country codes). |
| GS1 Tag Data Translation (TDT) | 2.3 (Public Review Draft) | Machine-readable JSON and XML schema definitions, syntax translation grammar, and bidirectional transformation rules between EPC formats. |
| GS1 Digital Link Standard | 1.2 |
URI structure parsing, AI key paths (e.g. /01/, /21/), attribute query strings, and canonical stem replacement (https://id.gs1.org).
|
| GS1 General Specifications | Release 26 (issued January 2026) | GS1 Company Prefix (GCP) allocation rules, dynamic length boundary lookup (6–12 digits), and Luhn modulo-10 check digit algorithms. |
| GS1 Application Identifiers Dataset | Canonical |
Machine-readable catalog of Application Identifiers, mandatory associations (requires), and mutual exclusions (excludes). Available as JSON-LD at GS1_Application_Identifiers.jsonld.
|
Tech Stack & Dependency Bill of Materials
#The application follows a strict zero-build, client-side Progressive Web App architecture. It is built to drop directly onto standard Apache 2.x webservers without requiring Node.js, npm scripts, bundlers (Webpack, Vite), or compiler toolchains.
| Component / Library | File / Version | Architectural Rationale |
|---|---|---|
| Vue.js (Global Build) | vue.global.js (v3.3.4) |
Reactive UI rendering using strictly the Options API (data, computed, watch, methods). Avoids Composition API build tooling.
|
| JSZip & JSZip-Utils | jszip.js, jszip-utils.js (v3.10.1) |
Client-side unzipping capability used as a backward-compatible fallback for reading TDT_JSON_artefacts.zip packages offline.
|
| Native Vanilla CSS | style.css |
Pure CSS without external framework overhead (no Bootstrap, no Tailwind CSS). Uses CSS custom properties for GS1 brand styling. |
| Service Worker | sw.js (Cache: tdt-translator-v1.0.6) |
Provides offline PWA resilience. Pre-caches core application files and dynamically caches unzipped JSON schema requests. |
| Web App Manifest | manifest.webmanifest |
PWA configuration specifying standalone execution mode and brand themes without locking viewport orientation. |
项目仓库目录结构
Standard file and folder layout of the GS1 TDS / TDT 2.3 Translator application repository:
TDT_2_3/ ├── index.html # Production PWA Single-Page Application (HTML5 user interface) ├── developer_guide.html # Self-contained Developer Architecture & Handover Guide ├── TDTtranslator.js # Core TDT 2.3 Translation Engine class (ES6 class, ~3,500 lines) ├── batch_translate.js # Standalone headless batch translation runner & automation script ├── createApp.js # Vue 3 Options API application instance and state orchestrator ├── style.css # Production Vanilla CSS styles (GS1 design system, zero frameworks) ├── vue.global.js # Vue 3.3.4 Global Build (zero-build reactive runtime) ├── jszip.js # JSZip v3.10.1 client-side unarchiving library ├── jszip-utils.js # JSZip AJAX / ArrayBuffer bridge loader ├── sw.js # Service Worker script (PWA offline caching, cache version v1.0.7) ├── manifest.webmanifest # PWA Application Manifest metadata ├── icon-192.png, icon-512.png # High-resolution PWA home screen application icons ├── gcpprefixformatlist.json # Optional GS1 Company Prefix format allocation list (~14 MB) ├── fonts/ # Local offline WOFF2 web fonts (Inter, Fira Code) │ ├── inter.woff2 # Inter UI typeface (weights 300..800) │ └── firacode.woff2 # Fira Code monospace typeface with coding ligatures (weights 400..700) ├── minimal_version_for_resolvers/ # Standalone lightweight resolver deployment example │ ├── index.html # Minimal resolver web UI for decompressing /eh and /ex Digital Links │ ├── createApp.js # Compact Vue 3 controller (<90 lines) invoking TDTtranslator │ ├── style.css # Streamlined dark-themed resolver stylesheet │ ├── test_minimal.html # Automated browser verification test harness │ ├── TDTtranslator.js # Core translation engine runtime copy │ └── schemas/ # Normative scheme definitions and lookup tables ├── schemas/ # Normative declarative scheme definitions (47 EPC schemes) and lookup tables │ ├── TDT_TableA.json # 7-bit subdomain and TLD optimization dictionary (TDS §14.5.16) │ ├── TDT_TableB1.json–B4.json# 14-bit extended domain partition tables (TDS §14.5.16) │ ├── TDT_TableB.json # Consolidated Table B offline reference dictionary │ ├── TDT_TableE.json # Prefix list & GCP partition lookup table (TDS §14.5.15) │ ├── TDT_TableF.json # AI compaction rules and bitlength dictionary (TDS §14.5.2–14) │ ├── SGTIN++.json # Extensible SGTIN schema definition with domain compaction │ └── ... # 46 other scheme definition files (47 EPC schemes total: SGTIN-96, GRAI-96, GIAI-96, SSCC-96, etc.) └── tests/ # Headless node verification and test harness scripts
权威 TDS 数据表与参考数据集
The engine relies on 9 normative JSON table artifacts located under the schemas/ directory. These artifacts provide lookup dictionaries, AI syntax rules, and compaction codes:
| Artifact File | TDS Section | Purpose & Internal Structure |
|---|---|---|
TDT_TableA.json |
§14.5.16 |
Subdomain & TLD 7-Bit Optimizations: High-frequency domain prefixes and suffixes mapped to 7-bit binary tokens (e.g. id. → 0100000, .com → 1011011).
|
TDT_TableB1.json – B4.json |
§14.5.16 | 14-Bit Extended Domain Optimizations: 4 split partition tables covering broader ccTLD and gTLD namespaces. Encoded as two 7-bit words (indicator prefix + offset). |
TDT_TableB.json |
§14.5.16 | Consolidated Table B Reference: Complete unpartitioned catalog used as an offline reference fallback for 14-bit domain compaction. |
TDT_TableE.json |
§14.5 | GS1 AI Validation Rules: Master specification for Application Identifiers, detailing data titles, character types, fixed/variable lengths, and regexes. |
TDT_TableF.json |
§14.5.1 | Compaction Methods for AIs: Maps each Application Identifier to its normative compaction section (§14.5.2 to §14.5.14) and specifies target bit capacities. |
TDT_TableK.json |
§14.5.6 | Character Compaction Codes: 7-bit ASCII character mapping table used for variable-length alphanumeric strings in §14.5.6. |
gcpprefixformatlist.json |
GenSpecs §1.4 | GCP Length Allocation Table: GS1 Company Prefix allocation rules allowing the engine to calculate prefix length (6–12 digits) from numeric identification keys. |
In legacy GS1 Tag Data Standards (TDS 1.x), schemes had fixed bit lengths and rigid partition tables (e.g. sgtin-96, sgtin-198, sscc-96, grai-96). These could only represent a single identification key with a fixed-length serial or item reference, and could not encode additional secondary Application Identifiers.
GS1 TDS 2.3 introduces the "++" suffix convention (such as SGTIN++, SSCC++, GRAI++, ITIP++). This designation denotes:
- Dynamic Multi-AI Payloads: Allows carrying arbitrary secondary Application Identifiers (e.g. AI 10 batch/lot, AI 17 expiration date, AI 21 serial) in the same physical RFID or barcode bitstream.
- Dynamic Compaction via Table F: Evaluates variable-length compression algorithms (§14.5) to pack data into the smallest possible bit sequence.
- Custom Domain Preservation: Retains non-canonical Digital Link URIs (e.g.
https://id.abcde.com/01/...) losslessly in binary through §14.5.16 hostname compaction, avoiding forced conversion tohttps://id.gs1.org.
数据表快速查看与字典查询
Inspect and search the loaded normative schema tables directly from memory without inspecting raw JSON files:
| {{ col }} |
|---|
{{ row[col] }}
|
| Showing first 50 of {{ filteredTableRecords.length }} matching records. Use the filter input above to narrow results. |
| No records match "{{ searchTableQuery }}". |
代码库集成示例与架构片段
Drop-in code patterns for integrating TDTtranslator.js across different runtime environments:
{{ recipeCodeBrowser }}
{{ recipeCodeWorker }}
{{ recipeCodeNode }}
无界面工具架构与批量转换
Developers building high-throughput batch conversion pipelines, microservices, or CLI tools can run TDTtranslator.js headlessly without the Vue.js user interface. The engine is an autonomous ES6 class with zero dependency on DOM APIs, Vue runtime, or CSS stylesheets. It executes natively in Node.js (v16+), AWS Lambda, worker threads, and headless container environments.
| Asset Path | Size on Disk | Status | Architectural Role & Headless Fallback |
|---|---|---|---|
TDTtranslator.js |
~176 KB | MANDATORY |
The core translation engine. Contains TDS §14.5 compaction algorithms, regex parsers, and bidirectional syntax mappings. In Node.js, automatically exports module.exports = TDTtranslator. In browsers, attaches to window.TDTtranslator.
|
schemas/ |
~1.4 MB | MANDATORY |
Schema directory containing 56 JSON files: master manifest.json, 9 lookup tables (TDT_TableA.json, TDT_TableB1–B4.json, TDT_TableB.json, TDT_TableE.json, TDT_TableF.json, TDT_TableK.json), and 47 scheme definitions (SGTIN++.json, SSCC++.json, GRAI++.json, etc.). Natively read via Node's fs module.
|
gcpprefixformatlist.json |
~14 MB | OPTIONAL |
GS1 Global Office prefix allocation table. Only needed when calling autodetect() on bare GTINs or GS1 Digital Link URIs where the GS1 Company Prefix length (6–12 digits) is completely unknown and must be dynamically looked up. Safely omitted when translating Tag URIs (where prefix dots delineate GCP boundaries) or when passing gs1companyprefixlength in options. When omitted in Node.js, the engine logs a debug notice and resolves cleanly.
|
index.html, developer_guide.html |
~220 KB | EXCLUDED | Browser-only graphical user interfaces and architecture documentation. Not required for headless CLI or microservice operations. |
createApp.js, vue.global.js, style.css |
~592 KB | EXCLUDED | Vue.js 3 presentation orchestrator, framework bundle, and stylesheet. The engine has zero dependency on Vue. |
sw.js, manifest.webmanifest, icon-*.png |
~60 KB | EXCLUDED | Browser Progressive Web App (PWA) offline service worker, web manifest, and application icons. Excluded from backend distributions. |
jszip.js, jszip-utils.js |
~370 KB | EXCLUDED |
Client-side zip decompression libraries. Only used in browsers when reading zipped schema packages. Node.js environments read the unzipped schemas/ directory directly via fs.
|
TDTtranslator.js and the schemas/ folder (~1.5 MB total). This represents a 90% reduction compared to the full browser bundle with the 14 MB prefix table (~16 MB).
Headless Engine Lifecycle & Batch Processing Rules
-
Single Instance Initialization: Instantiate
new TDTtranslator()once at service startup and awaittranslator.initialized, then invoketranslator.processData(). Never instantiate the translator inside a per-item loop because parsing 56 JSON schemas consumes CPU cycles and memory. Reusing a single instance processes items in 5–10 milliseconds each. -
Compaction Options: When translating into binary or hex representations under multi-AI schemes (e.g.
SGTIN++,SSCC++), TDS §14.5.16 compaction requiresfilter(e.g.0) anduriStem(e.g.'https://id.gs1.org') orhostname. -
Per-Item Error Boundaries: Wrap individual translation calls in
try...catchblocks. Different EPC schemes support different syntax levels (for example, multi-AI schemes do not supportPURE_IDENTITYTag URIs). Catching errors per level ensures that a single unsupported level does not halt the batch.
Production-Ready Batch Translation Script
Save the following script as batch_translate.js alongside TDTtranslator.js and the schemas/ directory:
{{ batchTranslateCode }}
$ node batch_translate.js
Initializing headless TDT 2.3 engine...
Engine ready in 82ms. Active schemes: 47
Batch translation complete: 5 items in 33ms (6.60ms/item)
[
{ "id": "item-01", "scheme": "SGTIN-96", "HEX": "3014257BF46DB64000000190", "DL": "https://id.gs1.org/01/10614141123459/21/400" },
{ "id": "item-02", "scheme": "SGTIN++", "HEX": "FD0095212341234538566CB0AFC515067E6C6E0", "DL": "https://id.gs1.org/01/09521234123453/21/32a%2Fb" },
{ "id": "item-03", "scheme": "SGTIN-96", "HEX": "3074257BF4003E0000000190", "DL": "https://id.gs1.org/01/00614141002481/21/400" },
{ "id": "item-04", "scheme": "SSCC-96", "HEX": "3114257BF4499602D2000000", "DL": "https://id.gs1.org/00/106141412345678908" },
{ "id": "item-05", "scheme": "SSCC++", "HEX": "EF01061414123456789088A833F36370", "DL": "https://id.gs1.org/00/106141412345678908" }
]
Embedding TDTtranslator.js in Custom Web Applications (Re-Skinning Guide)
Developers wishing to create custom front-end user interfaces or re-skin the tool (using React, Angular, Svelte, Lit, or plain handwritten Vanilla HTML/JS) can reuse TDTtranslator.js directly. The engine is entirely decoupled from the presentation layer:
-
Zero Framework Dependency:
TDTtranslator.jsdoes not require Vue.js, jQuery, or any third-party UI framework. In standard browser environments, loading<script src="TDTtranslator.js"></script>attaches the constructor directly towindow.TDTtranslator. -
Zero Zip Libraries Needed when Serving Unzipped Schemas: When deploying the
schemas/directory as unzipped static JSON files on your web server (Apache, Nginx, CDN, or local server), the engine natively uses the browser's standardfetch()API. You do not need to includejszip.jsorjszip-utils.jsin your application bundle. -
Managing the Asynchronous Lifecycle (
async/await): BecauseTDTtranslatordownloadsmanifest.jsonand all 56 schema files asynchronously over HTTP, developers must coordinate the engine lifecycle with their UI state:- Instantiate the engine:
const translator = new TDTtranslator(); - Wait for all schemas to download:
await translator.initialized; - Compile in-memory routing and optimization structures:
translator.processData(); - Enable user interface controls and start accepting inputs.
LOADING→READYorERROR) and disable translation inputs untilinitializedresolves to prevent race conditions. - Instantiate the engine:
{{ customWebSnippet }}
For developers building dedicated GS1 Digital Link resolvers, reverse proxies, or edge decompression services, the repository includes a self-contained, turnkey template in the minimal_version_for_resolvers/ directory:
minimal_version_for_resolvers/index.html: A stripped-down, focused single-page resolver interface for decompressing/eh...(Hex) and/ex...(Base64) compressed Digital Links without the overhead of full EPC scheme catalog tables.minimal_version_for_resolvers/createApp.js: A compact Vue 3 Options API controller under 90 lines illustrating direct invocation oftranslator.autodetect()andtranslator.translate(input, match.scheme, 'GS1_DIGITAL_LINK').minimal_version_for_resolvers/test_minimal.html: An automated browser-based verification test suite checking dual/ehand/exdecompression directly against the canonical GS1 Digital Link output.
高吞吐量 Web Worker 批量处理(界面保持响应)
While translating an individual barcode or EPC Tag URI on the browser's main thread takes approximately 5 milliseconds, batch processing hundreds or thousands of tags in a synchronous loop blocks the JavaScript event loop. This causes DOM freezes, halts CSS animations, and triggers browser "Page Unresponsive" warnings.
To maintain a fluid 60 FPS user experience during high-volume batch translation, offload the workload to a dedicated Web Worker thread:
- Dedicated Background Thread: Web Workers run on a separate OS thread, completely isolated from DOM rendering.
-
Real-Time Progress Streaming: Rather than waiting for the entire batch to finish, the worker streams incremental
PROGRESSevents (e.g.{ processed, total, percent }) back to the main UI thread to animate a progress bar smoothly. -
Fault-Tolerant Queue Processing: Per-item
try/catchboundaries ensure that individual malformed identifiers are recorded as errors while the remaining queue continues uninterrupted.
{{ webWorkerSnippet }}
{{ mainWorkerSnippet }}
Inputs, Outputs & Data Contracts
#The translation engine auto-detects and converts across 8 structural syntax levels. Every supported format is strictly mapped through declarative grammar expressions and option keys:
| Format Level | DOM Key | Syntax Pattern / Example | Lossless Boundary Note |
|---|---|---|---|
| GS1 AI String in JSON | GS1_AI_JSON |
{"01":"09521234123453", "21":"32a/b"} |
Stores raw key-value elements. GCP boundary inferred via prefix table. |
| GS1 Digital Link URI | GS1_DIGITAL_LINK |
https://id.gs1.org/01/09521234123453/21/32a%2Fb |
Canonical GS1 URI or custom domain (e.g. https://id.abcde.com/...). |
| Compressed Digital Link | COMPRESSED_GS1_DIGITAL_LINK |
https://example.com/eh30164596f40c0e5cbe991a83 (Hex)https://example.com/exMBZFlvQMDly-mRqD (Base64) |
Hex (/eh...) or file-safe/URI-safe Base64 (/ex...) bitstream in path segment. |
| Binary Encoded TDS Data | BINARY |
11110111100010010101001000010100... |
Direct bitstream sequence matching physical RFID or 2D symbol encodings. |
| Hex Encoded TDS Data | HEX |
F73095212341234538566CB0AFC4 |
Hexadecimal nibble representation of the underlying binary bitstream. |
| EPC Tag URI | TAG_ENCODING |
urn:epc:tag:sgtin-198:0.9521234.012345.32a%2F |
Explicitly specifies bit length, filter value, and GCP partition boundary. |
| EPC Pure URI | PURE_IDENTITY |
urn:epc:id:sgtin:9521234.012345.32a%2Fb |
Logical entity identity independent of physical carrier tag specifications. |
| Bare Identifier | BARE_IDENTIFIER |
gtin=09521234123453;serial=32a/b |
Semicolon-delimited master data element representation. |
规范测试向量矩阵
Reference test vectors validating cross-level translations across major GS1 EPC scheme families. Click the button below to copy the full suite of fixtures as a structured JSON test matrix:
| Scheme | Source Level | Test Input String | Expected HEX Output | Status | Action |
|---|---|---|---|---|---|
{{ v.scheme }} |
{{ v.inputLevel }} |
{{ v.input }} |
{{ v.expectedOutputs.HEX }} |
{{ vectorResults[v.name || v.scheme].passed ? ('✓ Passed (' + vectorResults[v.name || v.scheme].ms + 'ms)') : '✗ Failed' }} Not run |
EPC Scheme Directory & Bit Capacity Matrix
Reference catalog of all 47 GS1 Electronic Product Code (EPC) schemes supported by the translation engine:
EPC URN structures (TAG_ENCODING / PURE_IDENTITY) are exclusively supported on legacy TDS 1.x schemes (e.g. SGTIN-96, SSCC-96). All modern schemes introduced since TDS 2.0 onwards (+ and ++) drop support for EPC URN formats entirely, standardising on GS1 Digital Link URIs (https://...), Binary, Hex, and GS1 AI Key-Value structures. Tag URI Prefix and Pure Identity URI fields are therefore empty for all + and ++ schemes.
| EPC Scheme | Family | Primary AI | Header Bits (Binary / Hex) | Tag URI Prefix | Pure Identity URI | Action |
|---|---|---|---|---|---|---|
{{ sch.name }} |
{{ sch.family }} | {{ sch.primaryAI }} |
{{ sch.headerBits }} ({{ sch.headerHex }}) |
{{ sch.tagPrefix }}— |
{{ sch.purePrefix }}— |
EPC Partition Table & Floating Bit Boundary Explorer
In legacy 96-bit EPC schemes (such as SGTIN-96, SSCC-96, GRAI-96, GIAI-96, SGLN-96), TDS allocates a strictly fixed total bit budget for identification (e.g. 44 bits for SGTIN-96; 58 bits for SSCC-96). A 3-bit partition value (P ∈ 0..6) dynamically shifts the internal boundary between the GS1 Company Prefix (M bits) and the Item Reference or Serial Reference (N bits).
{{ currentPartitionData.name }} completely eliminates partition tables and the rigid 44-bit ceiling! Company Prefix and Item Reference are dynamically compacted using Table F Radix-100 base-128 compression. Arbitrary prefix lengths (6–12 digits) are accommodated without sacrificing serial number capacity.
{{ currentPartitionRow.partitionBits }})0 to {{ currentPartitionRow.maxGcpVal }} (10{{ selectedGcpLength }} − 1).{{ currentPartitionData.itemRefLabel }} integer range:
0 to {{ currentPartitionRow.maxItemRefVal }} (10{{ currentPartitionRow.itemRefDigits }} − 1).Notice that as GCP length increases from 6 to 12 digits, the partition bits slide from
110 to 000, allocating more bits to GCP (20 → 40) and fewer to {{ currentPartitionData.itemRefLabel }} (24 → 4).
System Architecture & Data Flow
#The system pipeline decouples the data models from translation mechanics. The lifecycle operates through four discrete stages:
[Input String]
│
▼
1. Auto-Detection ───► Regex pattern matching against all registered TDS scheme profiles
│
▼
2. Token Extraction ─► Slices fields, runs URLDECODE, maps AI keys (01, 21, etc.)
│
▼
3. Normalization ────► Identifies GCP length via gcpprefixformatlist.json (or override)
│
▼
4. Compaction Codec ─► Evaluates Table F rules; optimizes custom hostname (§14.5.16)
│
▼
5. Grammar Assembly ─► Concatenates literal header, filter, encoded AIs, and binary hostname
│
▼
[Output Representations] (Binary, Hex, Digital Link, Tag URN, Pure URN, Bare KV)
Regex Constants & Character Set Deconstruction
The translation engine relies on static regular expressions defined on the TDTtranslator class to validate data inputs and route tokens through syntax parsers:
| Constant Name | Expression | Matching Rationale & Standards Scope |
|---|---|---|
regexPermittedHostname |
^[!%-?A-Z_a-z\x22]+$ |
GS1 Digital Link Domain Scope (TDS §14.5.16): Validates permitted domain characters. %-? spans ASCII % (0x25) through ? (0x3F), covering digits 0-9, dot ., hyphen -, colon :, and slash /. \x22 permits the literal double-quote character.
|
regexURNcode40 |
^[A-Z0-9\.:-]+$ |
URN Code 40 Character Set (§14.5.16 Strategy 0): Validates characters supported by the 40-character alphabet. Strings containing lowercase characters or symbols outside ., :, - cannot use Strategy 0.
|
regexAlphanumeric |
^[\x21-\x23\x25-\x5A\x5F\x61-\x7A]+$ |
Table F Variable-Length Alphanumeric (§14.5.6): Defined verbatim on TDTtranslator.regexAlphanumeric. Validates printable 7-bit ASCII characters for general text AIs (e.g. serial numbers, batch/lot), spanning ASCII 0x21–0x23 (!-#), 0x25–0x5A (%-Z), 0x5F (_), and 0x61–0x7A (a-z), strictly excluding space (0x20), dollar sign (0x24), and backtick (0x60).
|
regexAllNumeric |
^[0-9]+$ |
Fixed and Numeric Compaction (§14.5.2 & §14.5.4): Strictly matches digits 0-9. Used by fixed-length numeric packing (Radix-100 (4 bits per character, where '100' is binary for 4) base-128 compression).
|
regexDateYYMMDD |
^[0-9]{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12][0-9]|30|31)$ |
Packed Date Format (§14.5.8): Validates 6-digit GS1 calendar dates with 2-digit year (00-99), 2-digit month (01-12), and valid calendar day (01-31).
|
regexRule |
^([A-Z0-9_]+)\((.+)\)$ |
Grammar Rule Invocation Parser: Captures the rule function name in Group 1 (e.g. URLDECODE, SUBSTRING, HOSTNAME2BINARY) and comma-separated arguments in Group 2.
|
Interactive Regex Pattern Sandbox
Test arbitrary character strings against core GS1 TDS 2.3 validation and grammar regular expressions in real time. Inspect match status, capture groups, and invalid character positions:
{{ regexSandboxResult.patternSource }}
方案初始化 & Unzipped Directory Loading
To ensure standard agility, all 9 Table definitions (TDT_TableA.json, TDT_TableB1-B4.json, TDT_TableF.json, etc.) and 46 scheme configurations reside unzipped under ./schemas/.
The private method #fetchDirectoryData(baseDir) loads manifest.json via HTTP fetch() in browsers, and maps each entry into memory cache arrays. If run in a Node.js test environment, it transparently falls back to fs.readFileSync.
GS1 Digital Link URI Parsing & Positional Grammar Deconstructor
GS1 Digital Link URIs encode identification keys, key qualifiers, and data attributes in web URIs. The translation engine executes digitalLinkPreFormat() and digitalLinkPostFormat() to decompose URIs into canonical components, normalize unordered query strings into standard positional sequence, decode URL-escaped entities (e.g. %2F → /), and format outputs across multiple GS1 syntaxes:
| AI | Attribute Description | Grammar Role | Raw Value | Normalized Value | Compaction Method |
|---|---|---|---|---|---|
| AI ({{ attr.ai }}) | {{ attr.title }} | {{ attr.role }} | {{ attr.rawVal }} |
{{ attr.normalizedVal }} |
{{ attr.compactionMethod }} |
{{ dlParsedResult.jsonString }}
https://id.gs1.org/01/09521234123453).
Hostname Compaction Architecture (TDS §14.5.16)
#
When converting a GS1 Digital Link with a custom domain (e.g. https://id.abcde.com/01/...) to an EPC binary string (such as SGTIN++), TDS 2.3 Section 14.5.16 defines two lossless compaction strategies:
- Strategy 0 (URN Code 40): Compresses 3 characters into a 16-bit word (approx. 5.33 bits/char). Indicator bit =
0. Only supports uppercase letters, digits, dot, hyphen, colon. - Strategy 1 (7-bit ASCII with Optimizations): Compresses subdomains and TLDs using pre-cached dictionary tables (Table A = 7 bits; Tables B1–B4 = 14 bits), falling back to raw 7-bit ASCII for unoptimized characters. Indicator bit =
1.
Interactive Hostname Compaction Strategy Comparator (TDS §14.5.16)
TDS 2.3 Section 14.5.16 evaluates two competing strategies in parallel to minimize tag bit occupancy for custom domains. Test any domain name to inspect intermediate tokenization and compare strategy outcomes in real time:
| Triplet | Indices (c1, c2, c3) | Polynomial Value | 16-Bit Word |
|---|---|---|---|
'{{ t.raw }}' |
{{ t.i1 }}, {{ t.i2 }}, {{ t.i3 }} | {{ t.val }} | {{ t.bin16 }} |
| Token Substring | Match Classification | Bit Length | Bit Sequence |
|---|---|---|---|
'{{ tok.str }}' |
{{ tok.source }} | {{ tok.bitLength }}b | {{ tok.bits }} |
internalBinary2Hostname(): {{ hostCompResult.decodedHost }}
In internalHostname2Binary, candidate tokens must be sorted first by character length descending, and if lengths are equal, by bit length ascending ((a.bitLength || a.binary.length) - (b.bitLength || b.binary.length)). This guarantees Table A (7-bit) entries take precedence over Table B (14-bit) entries.
Live Codec Playground & Bitstream Inspector
#
Test custom domain inputs and explore the live bitstream partitioning produced by the in-browser TDTtranslator engine:
• Engine selection: Strategy {{ playgroundResult.hostnameData.strategy }} ({{ playgroundResult.hostnameData.strategy === 1 ? '7-bit ASCII with Optimizations' : 'URN Code 40' }}), saving {{ Math.abs(playgroundResult.hostnameData.urnBits - playgroundResult.hostnameData.asciiBits) }} bits.
{{ selectedChunk.name }} ({{ selectedChunk.len }} bits)
Bit {{ selectedChunk.startBit }} – Bit {{ selectedChunk.endBit }} of {{ playgroundResult.totalBits }} total EPC bits.
| Sub-Field Component | Bit Length | Binary Value | Semantic Representation / Meaning |
|---|---|---|---|
| {{ sub.name }} | {{ sub.bits.length }} bits | {{ sub.bits }} |
{{ sub.meaning }} |
| Representation Level | Translated Output Value |
|---|---|
BINARY |
{{ playgroundResult.outputs.BINARY }}
|
HEX |
{{ playgroundResult.outputs.HEX }}
|
GS1_DIGITAL_LINK |
{{ playgroundResult.outputs.GS1_DIGITAL_LINK }}
|
TAG_ENCODING |
{{ playgroundResult.outputs.TAG_ENCODING }}
|
PURE_IDENTITY |
{{ playgroundResult.outputs.PURE_IDENTITY }}
|
GS1_AI_JSON |
{{ playgroundResult.outputs.GS1_AI_JSON }}
|
BARE_IDENTIFIER |
{{ playgroundResult.outputs.BARE_IDENTIFIER }}
|
Complete Codebase Reference Index
#
Granular API documentation for all public and private methods across TDTtranslator.js and createApp.js:
{{ method.description }}
| Parameter | Type | Description |
|---|---|---|
{{ p.name }} |
{{ p.type }} |
{{ p.desc }} |
Returns: {{ method.returns }}
{{ method.snippet }}
UI Components & State Exploration
#
The reactive controller (createApp.js) manages application state through the Vue 3 Options API:
主要状态属性 (data())
| Property | Type | Default | Role & Reactive Impact |
|---|---|---|---|
inputString |
string |
'' |
Bound to the main text field (#inputString). Triggers detectedData recalculation. |
filter |
number |
0 |
EPC filter value (0–7) applied to binary outputs when not specified by input. |
gcpLength |
number |
7 |
GS1 Company Prefix length. Auto-detected via prefix table unless overridden. |
gcpOverride |
boolean |
false |
Checkbox lock (#gcpOverride) forcing manual GCP length selection. |
uriStem |
string |
'https://id.gs1.org' |
Base URI stem used when rendering canonical GS1 Digital Link outputs. |
Computed Reactive Pipeline
detectedData: InvokesmyTDTencoder.autodetect(inputString)and returns matching candidate schemes and source level.structuredSchemes: Iterates through each supported candidate scheme, invokestranslate()across all target levels, builds color-coded HTML bit spans (span.binary0..span.binary9), and computes nibble and word boundary paddings.
响应式状态流程
Data flow cascade through the Vue 3 Options API reactive pipeline upon user interaction:
User Input Event (#inputString input change or .btn-demo click) │ ▼ State Mutation: this.inputString updated │ ▼ Computed Property: detectedData ├── Invokes TDTtranslator.autodetect(this.inputString) └── Returns matching candidate schemes, detected source level, and grammar options │ ▼ Computed Property: structuredSchemes ├── Iterates through detected candidate schemes (e.g. SGTIN++, SGTIN-96) ├── Resolves GCP length (auto-detected via TDT_TableE.json or overridden by #gcpOverride) ├── Executes TDTtranslator.translate(...) for each target syntax level ├── Computes color-coded bit partition segments (span.binary0 .. span.binary9) └── Pre-computes formatted HEX, GS1 Digital Link, and Tag URI output representations │ ▼ DOM Render Cascade (v-for="scheme in structuredSchemes") ├── Updates scheme card headers, total bit counts, and source badges ├── Renders color-coded bitstream block visualizer └── Renders output representation table with 1-click clipboard copy triggers
DOM 元素与指令映射
Mapping between user interface DOM elements, Vue 3 template directives, and underlying reactive handlers:
| DOM Element / Selector | Vue Directive | Trigger Event | Reactive Role & Controller Logic |
|---|---|---|---|
#inputString |
v-model.trim="inputString" |
@input |
Main user input field. Triggers automatic re-computation of detectedData. |
.btn-clear-input |
@click="inputString = ''" |
@click |
Resets user input field and clears candidate schemes. |
.btn-demo |
@click="loadDemo(key)" |
@click |
Loads preset test vector strings across 8 syntax levels. |
#filter |
v-model.number="filter" |
@change |
Specifies fallback EPC filter value (0–7) passed to translate() options. |
#gcpLength |
v-model.number="gcpLength" |
@change |
Manual GCP length (6–12 digits). Disabled unless gcpOverride is true. |
#gcpOverride |
v-model="gcpOverride" |
@change |
Checkbox toggling manual override vs prefix table auto-detection. |
#uristem |
v-model.trim="uriStem" |
@input |
Base URI stem used when rendering GS1 Digital Link outputs. |
.scheme-container |
v-for="scheme in structuredSchemes" |
Reactive update | Renders translated output cards for each valid EPC scheme candidate. |
.btn-copy-code |
@click="copyOutput(val, id)" |
@click |
Writes translated level output to clipboard with temporary visual feedback. |
Maintenance, Extension & Succession Guide
#Concrete instructions for future developers maintaining this codebase:
交互式 Table F 压缩计算器
Test how GS1 Application Identifiers compact into binary sequences under TDS Section 14.5. Select a preset or input custom values to inspect bit lengths and mathematical formulas:
Table F 压缩算法矩阵 (TDS §14.5.2 – §14.5.14)
The GS1 Tag Data Standard defines specialized encoding algorithms to pack Application Identifier values into high-density bitstreams:
| TDS Section | Compaction Method | Input Data Type | Compaction Algorithm & Bit Economy |
|---|---|---|---|
§14.5.2 |
Fixed Bit-Length Integer | Numeric (fixed range) | Converts a fixed decimal integer directly into N binary bits. Example: 3-bit filter value (0–7). |
§14.5.4 |
Fixed-Length Numeric | Numeric digits | Radix-100 (4 bits per character, binary 100 = 4) Base-128 Compaction: Compresses pairs of decimal digits into 7-bit chunks (100 values fit in 128 states). Compresses a 14-digit GTIN from 56 bits down to 49 bits (~17% reduction). |
§14.5.6 |
Variable-Length Alphanumeric | ASCII string | Encodes characters using 7-bit ASCII preceded by a bit-length indicator field specifying character count. |
§14.5.8 |
Date YYMMDD | 6-digit calendar date | 16-Bit Packed Calendar: Calculates day offset from century base year. Encodes any valid date in 16 bits (saving 32 bits compared to ASCII). |
§14.5.10 |
Date & Time YYMMDDhhmm | 10-digit timestamp | 28-Bit Packed Timestamp: Encodes year, month, day, hour, and minute into a single 28-bit integer. |
§14.5.12 |
Country Code | 3-digit ISO 3166-1 | Encodes 3-digit numeric country code (000–999) into 10 binary bits (1024 states). |
Interactive Luhn Modulo-10 Check Digit Calculator
GS1 identification keys (GTIN-8, GTIN-12, GTIN-13, GTIN-14, and SSCC-18) employ the standard Modulo-10 check digit algorithm defined in GS1 General Specifications Section 7.9. Calculate check digits for raw data payloads or validate existing full identifiers:
| Position (R→L) | Digit | Weight | Calculation | Product | Running Sum |
|---|---|---|---|---|---|
{{ step.posR2L }} |
{{ step.digit }} | {{ step.weight }}x | {{ step.digit }} × {{ step.weight }} | {{ step.product }} |
{{ step.runningSum }} |
Common Pitfalls, Error Diagnostics & Troubleshooting
Reference diagnostics and resolutions for frequent runtime errors encountered during TDT development and deployment:
| Error Signature / Symptom | Underlying Root Cause | Diagnostic & Resolution Procedure |
|---|---|---|
TDTExtractionError: Scheme does not match format |
Input character string fails regex pattern matching defined under the scheme's option definition in schemas/*.json.
|
Verify input against the character sets deconstructed in Section 4. Ensure Application Identifier prefixes (e.g. (01) vs /01/) and serial character classes conform to GS1 General Specifications.
|
CORS error: Cross origin requests are only supported for HTTP / HTTPS |
Attempting to launch index.html or developer_guide.html via local file:// protocol. Browser security blocks fetch() for schema tables.
|
Always serve through a local static HTTP server: python3 -m http.server 8000 or deploy to an Apache 2.x virtual host.
|
Service Worker stale cache / Schema updates not reflected |
Browser serves previously cached JSON table files from the Service Worker cache without checking the network. |
Increment the cache version identifier in sw.js (e.g. from tdt-translator-v1.0.6 to v1.0.7) or clear browser storage via DevTools > Application > Clear site data.
|
Check Digit calculation error (modulo 10) |
GTIN, SSCC, or GRAI check digit mismatch during grammar assembly or validation rule evaluation. |
Verify padDecimal length formatting. Ensure the check digit position in grammar matches the target representation and check digit algorithm parameters in rule.
|
Radix-100 (4 bits per character) Base-128 parity / length discrepancy |
Odd number of decimal digits passed to Table F §14.5.4 compaction without required half-byte padding. |
Check schemas/TDT_TableF.json field specifications. The compaction codec requires even-length digit strings or explicit zero-padding indicators defined by the standard.
|
TDS Scheme Definition File Anatomy (e.g. schemas/SGTIN++.json)
Every declarative scheme file in schemas/ defines the bidirectional mapping across representation levels through five core structural pillars:
{
"level": [ ... ], // 1. Structural levels supported (BINARY, GS1_DIGITAL_LINK, TAG_ENCODING, etc.)
"option": [ ... ], // 2. Encoding options per level (patterns, filter options, bitlengths)
"field": [ ... ], // 3. Field components (header, filter, companyPrefix, itemReference, serial, hostname)
"grammar": [ ... ], // 4. Assembly sequences concatenating fields and literals for target outputs
"rule": [ ... ] // 5. Normalization, URL decoding, check digit, and Table F compaction rules
}
1. Adding a New GS1 Application Identifier (AI)
- Open
schemas/TDT_TableF.json. - Add a new JSON record for the Application Identifier with its assigned compaction method:
{ "a": "8020", "b": "Variable-length alphanumeric", "c": "14.5.6", "f": "3", "g": "5", "h": "25" } - If the new AI requires a new encoding algorithm, add the encoder and decoder methods to
TDTtranslator.jsand map them inget tds2encodingMethods().
2. Updating Hostname Optimization Tables (Table A / Table B)
- When GS1 updates subdomains or TLDs in the Tag Data Standard, replace
schemas/TDT_TableA.jsonorschemas/TDT_TableB1.jsonthroughB4.jsonwith the new authoritative exports. - Do not hardcode entries inside JavaScript.
TDTtranslator.jswill dynamically ingest the updated JSON tables upon page reload.
3. Adding a New EPC TDS Scheme
- Drop the new scheme definition file (e.g.
NEWKEY++.json) intoschemas/. - Register the file inside
schemas/manifest.jsonunderdefinitionFiles.
4. Running Local Verification Tests
Run automated end-to-end test suites locally without build tools:
# Start a local static HTTP server
python3 -m http.server 8000
# Run headless verification test runner
node test_minimal_suite.js
# Or open test runners directly in your browser:
# http://localhost:8000/test.html
# http://localhost:8000/minimal_version_for_resolvers/test_minimal.html